CustomURLCache of NSURLCache with download function in Objective-c

Source: Internet
Author: User

CustomURLCache of NSURLCache with download function in Objective-c

I recently encountered this problem during iOS APP development: I developed a reading App, and the text interface is implemented through UIWebViewController, now we need to implement the offline reading function of the article. This means that all resource request results on the current web page are downloaded locally. I found many methods on the Internet and found that they are not very good. Later, I decided to start with the cache: NSURLCache of iOS does not support downloading the cache to a custom directory. Therefore, only the NSURLCache class can be rewritten to implement these functions. I found a CustomURLCache class written by others on the Internet, but the program collapsed during use. So I debug the code step by step, locate the class error, and modify the code, fixed this bug. With the release of iOS8, it is found that the user-defined URLCache must be in the AppDelegate. m- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptionsFunction, otherwise it is invalid. But I had to modify the code further. Finally, we can adapt to ios8. I will share this part of the code today and hope it will be useful to you. The Code has been hosted on github. You can download it on your own.

At the same time, to be compatible with the NSURLCache function of the system, CustomURLCache has two modes: NORMAL_MODE and DOWNLOAD_MODE. The CustomCache and NSURLCache functions in NORMALMODE are the same; the downmurlcache in DOWNLOADMODE can be used to download sub-functions that contain custom download directories and set expiration time.

The following example shows how to use the CustomURLCache class. Suppose we are creating a reading App, and the text page is displayed using UIWebViewController. Now we need to implement an offline download function to save all the resources (html files, images, JavaScript, CSS, etc.) accessed on the current webpage to the local device. You can use CustomURLCache to easily implement this function.

Set CustomURLCache to global URLCache in AppDelegate. m.

As mentioned above, in iOS8, setting global URLCache must be in AppDelegate. m.- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptionsSo the first step is to set CustomURLCache to global URLCache in this function:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    ......    //Init custom cache        CustomURLCache *_mCache = [[CustomURLCache alloc] initWithMemoryCapacity:20 * 1024 * 1024                                                diskCapacity:200 * 1024 * 1024                                                    diskPath:nil                                                   cacheTime:0                                                subDirectory:nil];    [NSURLCache setSharedURLCache:_mCache];    return YES;}

This code sets CustomURLCache as a global URLCache. The parameters in this Code have the following meanings:

  • DiskCapacity: indicates the size of the cache set by the user.
  • DiskPath: the download path of the cache. If it is set to nil, this class will automatically use the cache directory of the current application as the download path.
  • CacheTime: cache expiration time. If it is set to 0, the cache will never expire.
  • SubDirectory: This is a subDirectory under diskPath, which indicates the subDirectory in which the current cache will exist. However, you only need to set it to nil during initialization.

    It is worth noting that there is no change after initialization, because the default mode at this time is NORMAL_MODE, that is, it is the same as NSURLCache. So there is no difference. Don't worry. Soon we will need to use DOWNLOAD_MODE.

    Set CustomURLCache to DOWNLOAD_MODE

    Now, if we select an article on the first page and click the text page, the layout of the text page is very simple.UIWebView, We need to use it to display a webpage and download all the resources that need to be requested to a local custom directory. DOWNLOAD_MODE is required at this time. The implementation is very simple.- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNilOrinitSet CustomURLCache to DOWNLOAD_MODE in the function:

    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];    if (self) {                ......            _mCache = (CustomURLCache *)[NSURLCache sharedURLCache];        [_mCache changeToDownloadMode:_subDir];        [NSURLCache setSharedURLCache:_mCache];    }    return self;}

    Now we can set CustomURLCache to download mode.[_mCache changeToDownloadMode:_subDir];You need to specify the download subdirectory, which is located in the download subdirectory under diskPath. All the web request resources will be downloaded to our custom directory.

    Restore CustomURLCache to NORMAL_MODE

    Now the web page is displayed, and all the web request resources are downloaded to the local device, so it is time to exit. Go back to the first page without DOWNLOAD_MODE. We need to restore it to NORMAL_MODE, add the following code to the dealloc function under UIViewController or other user-defined exit functions (here I am using my exit function ):

    -(Void) backToMainpage :( id) sender {if (no longer requires the article cache) {NSLog (@ "delete the article cache"); [_ mCache removeCustomRequestDictionary];} else {// do nothing} // no longer use the custom cache, but switch to the system cache [_ mCache changeToNormalMode]; [self. navigationController popViewControllerAnimated: YES];}

    Well, if you haven't deleted the article cache, then when we look at the text page again, you will find that the page will be added soon. The reason is very simple. When you enter the UIViewController again, the program will execute[_mCache changeToDownloadMode:_subDir];At this time, CustomURLCache first goes to the _ subDir path to check whether there are cached resources when receiving a URL request. If it is found and does not expire, it will be automatically added to the local resources, if not found or expired, the request will be sent over the network again. So you know why it's done so quickly, because all the resources are local!

    Now, we will briefly introduce it here. I hope to help you. At the same time, if you like it, please fork or below on GitHub. Thank you very much!

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.