Ios-oc-app hot Update, dynamic update (imitation QQ to turn a feature on or off)

Source: Internet
Author: User

I. PrefaceiOS Development Update app I think is the comparison pit is the audit time is relatively long, the audit is relatively strict, for just the small partners, the mine area is more, so hot update is more important;we may find that our commonly used QQ now down is more than 100 trillion, but after a few months to find that QQ in the mobile phone occupies a multi-g memory, especially the small cell phone memory smaller partners, this is because you in the process of use, there are some features you download down;
two. Create the framework1. New ProjectCreate a new Cocoa Touch framework project, and then write your new features in this project, like I created a controller that loads a picture and a label in the controller;
<span style= "FONT-SIZE:18PX;" >-(void) uiconfig{    self.title = @ "This is function 2";        Uiimageview *imageview = [[Uiimageview alloc]init];    Imageview.frame = CGRectMake (0, 0, screenwidth, screenheight);    NSData *data = [NSData datawithcontentsofurl:[nsurl urlwithstring:@ "http://img4.duitang.com/uploads/item/201405/31/ 20140531174207_hh5u4.thumb.700_0.jpeg "];    Imageview.image = [UIImage imagewithdata:data];    [Self.view Addsubview:imageview];        UILabel *label = [[UILabel alloc]init];    Label.backgroundcolor = [Uicolor clearcolor];    Label.frame = CGRectMake (0, (ScreenHeight-100)/2, screenwidth, +);    Label.numberoflines = 0;    Label.text = @ "This is the feature 2 which is the feature 2 which is the function of 2 which is the function of 2 which is the function of 2 which is the function of 2 which is the function of 2 which is the function 2 which is function 2 which is the function of 2 which is the function 2 which is the function 2 which is the function 2";    [Self.view Addsubview:label];} </span>
2. Add AggregateCreate a new aggregate inside the targets

3. Add a Run script

4. Script Source Code
<span style= "FONT-SIZE:18PX;"  ># sets the target folders and the final framework product.# if the project name and the framework's target name are different, customize fmkname# for example: Fmk_name = "Myframework" fmk_name=${project_name}# Install dir'll be, the final output to the framework.#, the following line create It in the root folder of the current project. install_dir=${srcroot}/products/${fmk_name}.framework# working DIR would be a deleted after the framework creation. wrk_dir=builddevice_dir=${wrk_dir}/release-iphoneos/${fmk_name}.frameworksimulator_dir=${wrk_dir}/ release-iphonesimulator/${fmk_name}.framework#-configuration ${configuration}# clean and Building both Architectures.xcodebuild-configuration "Release"-target "${fmk_name}"-sdk Iphoneos clean Buildxcodebuild- Configuration "Release"-target "${fmk_name}"-sdk iphonesimulator clean build# Cleaning the oldest.if [-d] ${install_dir } "]THENRM-RF" ${install_dir} "Fimkdir-p" ${install_dir} "Cp-r" ${device_dir}/"" ${install_dir}/"# Uses the Lipo Tool to Merge both BInary files (i386 + armv6/armv7) into one Universal final product.lipo-create "${device_dir}/${fmk_name}" "${simulator_di R}/${fmk_name} "-output" ${install_dir}/${fmk_name} "Rm-r" ${wrk_dir} "open" ${install_dir} "</span>

5. Run the packagerun the project, compress the generated framework package zip, and then upload the server;Example:http://7xqdun.com1.z0.glb.clouddn.com/FunctionZFJ1.framework.zip
three. Create a projectin the project we mainly download and read the framework package, we first want to get a list of features, where I wrote a list of features in the local, if you can use to get the list of functions on the server;1. Create Feature List dataI added four function modules, there is nsuserdefaults inside, wherein function 1 and function 2 have, others not; function 1 is a nsobject, function 2 is a controller directly; isopen:1 means open, 0 means close;
-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions {//    Override point for customization after application launch.    Self.window = [[UIWindow alloc] initwithframe:[[uiscreen mainscreen] bounds]];    Self.window.backgroundColor = [Uicolor Whitecolor];        [Self.window makekeyandvisible];    Add fake Feature list Nsarray *functionlist = [User_default objectforkey:@ "FunctionList"];        if (Functionlist==nil | | functionlist.count==0) {Nsarray *titlearr = @[@ "Function 1", @ "function 2", @ "function 3", @ "function 4"];        Nsarray *classname = @[@ "Hotupdatecontrol", @ "Zfjviewcontroller", @ "", @ ""];        Nsarray *classtype = @[@ "NSObject", @ "Uiviewcontroller", @ "", @ ""];                               Nsarray *downurl = @[@ "Http://7xqdun.com1.z0.glb.clouddn.com/HotMudel.framework.zip",                               @ "Http://7xqdun.com1.z0.glb.clouddn.com/FunctionZFJ1.framework.zip",  @"",                               @""];      Nsmutablearray *functionarr = [[Nsmutablearray alloc]init];            for (int i = 0; i<titlearr.count; i++) {nsmutabledictionary *dict = [[Nsmutabledictionary alloc]init];            [Dict Setobject:titlearr[i] forkey:@ "name"];            [Dict setobject:classname[i] forkey:@ "ClassName"];            [Dict setobject:classtype[i] forkey:@ "ClassType"];            [Dict setobject:@ (i) forkey:@ "mid"];            [Dict setobject:@ "0" forkey:@ "isopen"];//0 not open 1 open [dict setobject:downurl[i] forkey:@ "Downurl"];        [Functionarr addobject:dict];        } [User_default Setobject:functionarr forkey:@ "FunctionList"];    [User_default Synchronize];    } Dynamicviewcontroller *DVC = [[Dynamicviewcontroller alloc]init];    Uinavigationcontroller *NVC = [[Uinavigationcontroller ALLOC]INITWITHROOTVIEWCONTROLLER:DVC];        Self.window.rootViewController = NVC; return YES;}

2. Display Feature Listthe feature list is mainly used to show all the features that have been opened, that is, all the functions of isopen 1;A. Get all the Open data locally and then display it on the TableView
-(void) getdatabase{    [Self.dataarray removeallobjects];    Nsarray *functionlist = [User_default objectforkey:@ "FunctionList"];    For (Nsdictionary *dict in functionlist) {        Nsinteger isopen = [dict[@ "IsOpen"] integervalue];        if (isopen==1) {            [Self.dataarray addobject:dict];        }    }    [Self.tableview Reloaddata];}

B. Click on the Tableviewcell to jump to the corresponding framework to read out the methodNote that I store different frameworks under different folders, with mid as a distinction;
-(void) TableView: (UITableView *) TableView Didselectrowatindexpath: (Nsindexpath *) indexpath{[TableView    Deselectrowatindexpath:indexpath Animated:yes];    Nsdictionary *dict = Self.dataarray[indexpath.row]; Get the path name of the framework, I have mid-differentiate nsstring *destinationpath = [Nshomedirectory () stringbyappendingstring:[nsstring    stringwithformat:@ "/documents/functionzfj%@", dict[@ "mid"]];    nsarray* arrframework = [self getfilenamelistoftype:@ "framework" fromdirpath:destinationpath];    NSString *bundlepath = [NSString stringwithformat:@ "%@/%@", Destinationpath,[arrframework LastObject]]; if (![        [Nsfilemanager Defaultmanager] Fileexistsatpath:bundlepath] {NSLog (@ "file does not exist");    Return    } nsbundle *bundle = [NSBundle Bundlewithpath:bundlepath]; if (!bundle | |![    Bundle Load]) {NSLog (@ "Bundle loading error");    } nsstring *classname = dict[@ "ClassName"];        NSString *classtype = dict[@ "ClassType"];    Class loadclass = [bundle classnamed:classname]; if (!loadClass) {NSLog (@ "Get failed");    Return        } if ([ClassType isequaltostring:@ "NSObject"]) {nsobject *bundleobj = [LoadClass new];        Nsarray *ARRVC = [bundleobj performselector: @selector (Getvcs)];        Tabcontroller *TVC = [[Tabcontroller ALLOC]INITWITHVCARRAY:ARRVC];    [Self.navigationcontroller PUSHVIEWCONTROLLER:TVC Animated:yes]; }else if ([ClassType isequaltostring:@ "Uiviewcontroller"]) {Uiviewcontroller *UVC = (Uiviewcontroller *) [LoadClass N        EW];    [Self.navigationcontroller PUSHVIEWCONTROLLER:UVC Animated:yes]; }}

C.


3. More FeaturesHere we can open or close a function;A. Get the function, including opening or closing the state, and then displaying it on the TableView;
<span style= "FONT-SIZE:18PX;" > #pragma mark-Get all data-(void) getdatabase{    [Self.dataarray removeallobjects];        Nsarray *functionlist = [User_default objectforkey:@ "FunctionList"];    Nsmutablearray *openyes = [[Nsmutablearray alloc]init];    Nsmutablearray *openno = [[Nsmutablearray alloc]init];    For (Nsdictionary *dict in functionlist) {        nsmutabledictionary *mudict = [[Nsmutabledictionary alloc] INITWITHDICTIONARY:DICT];        Nsinteger isopen = [mudict[@ "IsOpen"] integervalue];        if (isopen==1) {            //features already open            [Openyes addobject:mudict];        } else{            //No open function            [Openno addobject:mudict];}    }        [Self.dataarray Addobject:openno];    [Self.dataarray Addobject:openyes];        [Self.tableview Reloaddata];} </span>

B. Open function to open a function is to download the corresponding framework, unzip the downloaded zip package and then get to the framework, then delete the zip package, put the framework in the directory ; The state of the local list function is changed;
<span style= "FONT-SIZE:18PX;"  > #pragma mark-open a feature to download data first-(void) Ssziparchivedatabasewithdict: (nsmutabledictionary *) dict{nsstring *requesturl =    dict[@ "Downurl"]; if (Requesturl==nil | | requesturl.length==0) {self.progresslabel.text = [nsstring stringwithformat:@ "%@-No, can't open!", di        ct[@ "Name"]; Uialertcontroller *alertcontroller = [Uialertcontroller alertcontrollerwithtitle:@ "hint" message:@ "no, Cannot open"        Preferredstyle:uialertcontrollerstylealert];        Uialertaction *surebtn = [uialertaction actionwithtitle:@ "OK" style:uialertactionstyledefault Handler:nil];        [Alertcontroller ADDACTION:SUREBTN];        [Self Presentviewcontroller:alertcontroller animated:yes completion:nil];    Return }//Download saved path nsstring *savedpath = [Nshomedirectory () stringbyappendingstring:[nsstring stringwithformat:@ "/Documents    /functionzfj%@.framework.zip ", dict[@" mid "]];    Afhttprequestserializer *serializer = [Afhttprequestserializer serializer]; Nsmutableurlrequest *rEquest = [Serializer requestwithmethod:@ "POST" Urlstring:requesturl Parameters:nil Error:nil];    Afhttprequestoperation *operation = [[Afhttprequestoperation alloc]initwithrequest:request];    [Operation Setoutputstream:[nsoutputstream Outputstreamtofileatpath:savedpath Append:no]; [Operation setdownloadprogressblock:^ (Nsuinteger bytesread, Long long totalbytesread, long long        Totalbytesexpectedtoread) {Float progress = (float) totalbytesread/totalbytesexpectedtoread;    Self.progresslabel.text = [NSString stringwithformat:@ "%@ Download Progress:%.2f", dict[@ "name"],progress];    }]; [Operation setcompletionblockwithsuccess:^ (afhttprequestoperation *operation, id responseobject)        {NSLog (@ "Download succeeded"); NSString *destinationpath = [Nshomedirectory () stringbyappendingstring:[nsstring stringwithformat:@ "/Documents/        functionzfj%@ ", dict[@" mid "]];        Unzip the downloaded zip package BOOL Isscu = [ssziparchive unzipfileatpath:savedpath Todestination:destinationpath]; if (Isscu) {            NSLog (@ "unzip successfully");            Nsfilemanager *filemgr = [Nsfilemanager Defaultmanager];            BOOL BRet = [Filemgr Fileexistsatpath:savedpath]; if (bRet) {[Filemgr Removeitematpath:savedpath error:nil];//Extract succeeded after extracting the compressed package} [Dict Setva            lue:@ "1" forkey:@ "IsOpen"];        [Self updatabasewithdict:dict];//update local feature List status}else{NSLog (@ "Decompression failed---on failed");            }} failure:^ (Afhttprequestoperation *operation, Nserror *error) {NSLog (@ "Download failed---open failed");    }]; [Operation start];} </span>
Update Local Data
<span style= "FONT-SIZE:18PX;" > #pragma mark-Update local data-(void) Updatabasewithdict: (nsmutabledictionary *) dict{    Nsinteger mid = [dict[@ "Mid"] IntegerValue];    Nsmutablearray *functionlist = [User_default objectforkey:@ "FunctionList"];    Nsmutablearray *dataarr = [[Nsmutablearray alloc]initwitharray:functionlist];    [Dataarr Replaceobjectatindex:mid withobject:dict];    [User_default setobject:dataarr forkey:@ "FunctionList"];    BOOL Isscu = [User_default synchronize];    if (Isscu) {        [self getdatabase];//re-fetch data Update list        if (self.refreshdata) {            self.refreshdata ();        }    } else{        NSLog (@ "C operation failed");}    } </span>

c. Shutdown functionturn off a feature, that is, remove the framework of a feature, and then change the status of the feature list;
<span style= "FONT-SIZE:18PX;" > #pragma mark-turn off a feature-(void) Delectfunctionzfjwithdict: (nsmutabledictionary *) dict{    Nsfilemanager *filemgr = [ Nsfilemanager Defaultmanager];    NSString *savedpath = [Nshomedirectory () stringbyappendingstring:[nsstring stringwithformat:@ "/Documents/ functionzfj%@ ", dict[@" mid "]];    BOOL BRet = [Filemgr Fileexistsatpath:savedpath];    if (bRet) {        nserror *err;        Turning off a feature is removing the local framework  and then modifying the local functional state        BOOL Isscu = [filemgr removeitematpath:savedpath error:&err];        if (Isscu) {            [dict setvalue:@ "0" forkey:@ "isopen"];            [Self updatabasewithdict:dict];        } else{            NSLog (@ "close failed");        }    } else{        NSLog (@ "close failed");}    } </span>

d.

four. Source Codein this there are, two framework source code, can project code;Note that if there is more than one function of the framework, remember that multiple framework names cannot be duplicated in the same function, otherwise the tuning fails;Link: https://pan.baidu.com/s/1mieyk3I Password: mg4m
Five.







Ios-oc-app hot Update, dynamic update (faux QQ to turn a feature on or off)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.