How to disable caching from NSURLSessionTask

后端 未结 7 602
终归单人心
终归单人心 2020-12-04 23:24

In my iOS app, I am using NSURLSessionTask to download json data to my app. I discovered that when I call the url directly from the browser, I get an up to date

相关标签:
7条回答
  • You need to set the cachePolicy on NSURLRequest, here's the documentation.

    Here's some insight as to how caching works in general.

    You can read about the specific enums you can use for specifying the cachePolicy here in particular:

    enum
    {
       NSURLRequestUseProtocolCachePolicy = 0,
       NSURLRequestReloadIgnoringLocalCacheData = 1,
       NSURLRequestReturnCacheDataElseLoad = 2,
       NSURLRequestReturnCacheDataDontLoad = 3,
    };
    typedef NSUInteger NSURLRequestCachePolicy;
    

    For example, you would do:

    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
    
    0 讨论(0)
  • 2020-12-04 23:56

    The below code worked for me, the catch is setting URLCache to nil.

     NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
        config.URLCache = nil;
    
    0 讨论(0)
  • 2020-12-05 00:04

    I was getting cache image for same url .. so i have done this

    imageView.imageFromUrl(self.shareData.userResponseData["photo"] as! String)
    
    extension UIImageView {
    
    public func imageFromUrl(urlString: String) {
    
        if let url = NSURL(string: urlString) {
    
            let request = NSURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 60.0)
    
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
    
                (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
                self.image = UIImage(data: data)
    
            }
        }
    }
    

    }

    0 讨论(0)
  • 2020-12-05 00:06

    Swift 3, Xcode 8

    extension UIImageView {
    func donloadImage(fromUrl url: URL) {
        let request = URLRequest(url: url, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 60.0)
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard
                let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
                let data = data, error == nil,
                let image = UIImage(data: data)
                else { return }
            DispatchQueue.main.async() { () -> Void in
                self.image = image
            }
        }.resume()
    }
    
    0 讨论(0)
  • 2020-12-05 00:15

    If your read the links from @runmad you can see in the flow chart that if the HEAD of the file is unchanged it will still used the cached version when you set the cachePolicy.

    In Swift3 I had to do this to get it to work:

    let config = URLSessionConfiguration.default
    config.requestCachePolicy = .reloadIgnoringLocalCacheData
    config.urlCache = nil
    
    let session = URLSession.init(configuration: config)
    

    That got a truly non-cached version of the file, which I needed for bandwidth estimation calculations.

    0 讨论(0)
  • 2020-12-05 00:20

    Rather than using the sharedSession, you also can create your own NSURLSession using a NSURLSessionConfiguration that specifies a default cache policy. So, define a property for your session:

    @property (nonatomic, strong) NSURLSession *session;
    

    And then:

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    self.session = [NSURLSession sessionWithConfiguration:configuration];
    

    Then requests using that session will use that requestCachePolicy.

    0 讨论(0)
提交回复
热议问题