Brief introduction
This article attempts to dynamically load a resource file from an indeterminate folder. The article continues to refine the custom imagenamed function and pave the next article.
The meaning of doing so
As we often say, most scenarios know that the meaning of doing things is often more meaningful than the way they do things. Meaning itself, often contains the purpose, the ultimate demand for a class of things, and methods, but we are temporarily looking for the purpose of achieving the ultimate goal of a viable means. The significance of knowing the meaning itself is that In the future, we may find a more appropriate way to achieve the purpose, that is, we say, to the richness of knowledge to a certain extent, many people in their personal skills in the process of improvement, how many will always have that kind of mastery, follow situation. To be sure, that kind of clairvoyant feeling, It is certainly not the result of a change in the number of lines of code, but more because of your search for the meaning of a particular coding requirement itself.
Specifically, why do we need dynamic resource folders? In terms of the information disclosed in the present discussion itself, it is mainly because our main.bundle is placed in the app, and the iOS app itself is packaged in files that are read-only on the user's phone. This expression has three meanings:
- If your resource file is placed in the APP's IPA package, it's not possible to try to update it directly-at least for a native IOS app;
- If your main.bundle is dynamically downloaded from the Web, each download is placed in a specific location of the user's folder, then you do not need to consider too many dynamic resource folders;
- If one day the iOS mechanism changes, or you write apps for other platforms, but their own app resource files are writable, then you may also be able to use the dynamic resource folder;
Reading a resource file from a specific cache directory
Reading the load resource file from a specific cache directory can be seen as a special form of a dynamic resource folder, so let's try to deal with this single situation first.
1. Dynamic stitching at a specific cache directory
In the iOS app, there's a difference between a pinned cache directory and a specific cache directory. The main reason is that each time the iOS app starts, its corresponding file directory is dynamically changing. That is, if we have the need to store file paths later, be sure to remember to store only files relative to the program sandbox home directory The relative path of the nshomedirectory. By the way, there are 3 visible subdirectories of the home directory's program home directory, namely: Documents , Library , tmp , details, can refer to blog: iOS sandbox file read/write
- Documents: Apple recommends that the files generated by the program creation and the file data generated by the app's browsing be saved in this directory, which is included in itunes backup and restore
- Library: The default settings or other status information of the stored program;
- Library/caches: Store the cache file, save the persisted data of the application, use it to apply the upgrade or save the data after the app is closed, and not be synced by itunes, so in order to reduce the time of synchronization, consider putting some larger files into this directory without needing backup.
- TMP: Provides an immediate place to create temporary files, but does not need to be persisted, after the application is closed, the data in the directory will be deleted, or the system may be cleared when the program is not running.
Now our resource directory, which is assumed to be pinned in relative directory Library/caches/patch , is named Main.bundle
So when needed, we can access our resource folders like this:
Nsarray * librarypaths =* Cachebundledir = [[librarypaths objectatindex:0] Stringbyappendingformat: @" /caches/patch/ " ]; NSLog (@ " Cache Resource Directory:%@"// Simulator Sample output: Cache Resource Directory:/users/yanfeng/library/ developer/coresimulator/devices/930159d0-850f-43ce-88d2-08be9d4a7e7f/data/containers/data/application/ ee3a92ab-2dbe-44c5-9103-11bac7aece15/library/caches/patch/
2.APP first time initialization, copy the resource file to a specific cache directory
NSString * Bundlename =@"Main.bundle"; Nserror* Err =Nil; Nsfilemanager* Defaultmanager =[Nsfilemanager Defaultmanager];if( ![Defaultmanager Fileexistsatpath:cachebundledir]) {[Defaultmanager createdirectoryatpath:cachebundledir withintermediatedirectories:yes attributes:nil Error:&err]; if(Err) {NSLog (@"Error initializing directory:%@", err); } nsstring* Defaultbundlepath =[[NSBundle Mainbundle].resourcepath stringbyappendingpathcomponent:bundlename]; NSString* Cachebundlepath =[Cachebundledir Stringbyappendingpathcomponent:bundlename]; [Defaultmanager copyitematpath:defaultbundlepath topath:cachebundlepath Error:&err]; if(Err) {NSLog (@"Error Copying initial resource file:%@", err); }}
Code, basically like the above, there are a few points I'd like to focus on:
- Fileexistsatpath Determines whether the cache directory is first started. This logic, in the real patch logic, is likely to be not strict, follow-up will use other methods, here enough can be;
- Createdirectoryatpath is used when the directory does not exist, first build the hierarchy of the directory, otherwise if copied directly, it is likely to error-depending on whether your copy of the target directory and the existing directory level difference is 1;
- Copyitematpath:topath: The topath is a complete and nonexistent target path and does not necessarily have the same name as the last-level path of the copyitematpath parameter. This is simplified only, and in the future if necessary, this function is capable of copying and renaming two operations at the same time, such as Main.bundle the name of a default.bundle ;
- The code is best placed in the APPDELEGATE.M ;
- On the emulator, you can easily see the effect after the function is executed: Right-click the Finder--Go to Folder--Enter the cache resource Directory for Xcode output.
3. Loading files from a specific cache directory
Because the directory is specific, we only need each time the app launches, according to the relative path to obtain the absolute path dynamically, and then get the cache directory main.bundle Resource Bundle path, then you can use the existing methods, from the bundle You can take pictures:
Nsarray * Librarypaths =nssearchpathfordirectoriesindomains (Nslibrarydirectory, Nsuserdomainmask, YES); NSString* Cachebundledir = [[Librarypaths objectatindex:0] Stringbyappendingformat:@"/caches/patch/"]; NSString* Bundlename =@"Main.bundle"; NSString* Imgname =@"[email protected]"; NSString* Bundlepath =[Cachebundledir Stringbyappendingpathcomponent:bundlename]; NSBundle* Cachemainbundle =[NSBundle Bundlewithpath:bundlepath]; NSString* Imgpath = [Cachemainbundle pathforresource:imgname ofType:@"PNG"]; UIImage* Image =[UIImage imagewithcontentsoffile:imgpath];self.sampleimageview.image= Image;
Reading a resource file from a dynamic cache directory
Here, mainly and implementation of iOS pictures and other resource files such as thermal update (II): Custom Dynamic Imagenamed class method combined with the extension, so that the original class extension support from the dynamic cache directory read Bundle, the idea itself is very simple, Just change the code below to determine where the bundle is located:
+ (UIImage *) imagenamed: (NSString *) imgname Bundle: (NSString *) bundlename cachedir: (NSString *) cachedir{Nsarray* Librarypaths =nssearchpathfordirectoriesindomains (Nslibrarydirectory, Nsuserdomainmask, YES); NSString* Cachebundledir =[NSBundle Mainbundle].resourcepath; if(cachedir) {Cachebundledir= [[[[Librarypaths Objectatindex:0] Stringbyappendingformat:@"/caches"] Stringbyappendingpathcomponent:cachedir]; } bundlename= [NSString stringWithFormat:@"%@.bundle", Bundlename]; Imgname= [NSString stringWithFormat:@"%@@3x", Imgname]; NSString* Bundlepath =[Cachebundledir Stringbyappendingpathcomponent:bundlename]; NSBundle* Mainbundle =[NSBundle Bundlewithpath:bundlepath]; NSString* Imgpath = [Mainbundle pathforresource:imgname ofType:@"PNG"]; UIImage*image; StaticNSString *model; if(!model) {Model=[[Uidevice Currentdevice]model]; } if([Model isequaltostring:@"IPad"]) {NSData* ImageData =[NSData Datawithcontentsoffile:imgpath]; Image= [UIImage imagewithdata:imagedata scale:2.0]; }Else{image=[UIImage Imagewithcontentsoffile:imgpath]; } returnimage;}
The original logic for loading the resource file from the IPA package can be overridden based on this method:
+ (UIImage *) imagenamed: (NSString *) imgname Bundle: (NSString *) bundlename{ return [self Imagenamed:imgname bundle:bundlename Cachedir:nil];}
+ (UIImage *) imagenamed: (NSString *) imgname Bundle: (NSString *) bundlename cachedir: (NSString *) Cachedir method C5>cachedir is also supported for multi-level catalogs, such as:
UIImage * image = [UIImage imagenamed:@ "sub/sample" Bundle:@ "main " cachedir:@"patch/default"= image;
Note that at this point the logic of the initial copy to the cache directory is also appropriate for the corresponding subdirectory changes:
Nsarray * librarypaths =* Cachebundledir = [[librarypaths objectatindex:0] Stringbyappendingformat: @" /caches/patch/default/ " ]; NSLog (@ " Cache Resource Directory:%@", Cachebundledir);
Reference resources:
- iOS sandbox file read/write
- This section is complete to execute Xcode engineering code, only 100k
- Series articles, exclusive GitHub projects
Implementing hot updates for resource files such as iOS pictures (iii): Dynamic resource Folder