标签: nsurlcache

3
推荐指数
1
解决办法
6202
查看次数

在 iOS 中清除内存警告的 url 缓存

NSURLCache收到内存警告时清除共享是一个好习惯吗?像这样的东西:

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}
Run Code Online (Sandbox Code Playgroud)

我是否正确地假设这也会不必要地清除磁盘缓存?

如果是这样,是否可以只清除内存缓存?

iphone didreceivememorywarning nsurlcache ios

3
推荐指数
1
解决办法
1937
查看次数

不会调用NSCachedURLResponse willCacheResponse

我们根据下面的缩写代码片段设置了一个简单的NSURLConnection和NSURLCache.我们已经确定服务器(localhost:9615)返回以下缓存头:

ETag : abcdefgh
Cache-Control : public, max-age=60
Run Code Online (Sandbox Code Playgroud)

但是,永远不会调用willCacheResponse委托方法.任何的想法?

码:

// In the app delegate
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];

// Triggered by a UIButton
- (IBAction)sendRequest:(UIButton *)sender {
    NSLog(@"sendRequest");
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:9615"] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
    NSMutableData *receivedData = [NSMutableData dataWithCapacity: 0];
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (!theConnection) {
        receivedData = nil;
    }
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
    NSLog(@"willCacheResponse");
    // ...
}
Run Code Online (Sandbox Code Playgroud)

nsurlconnection nsurlcache ios

2
推荐指数
1
解决办法
2134
查看次数

如何使用NSURLCache缓存NSURLProtocol提供的内容

我编写了一个NSURLProtocol将检查http针对plist本地路径映射的URL的出站请求并改为提供本地内容,然后使用它来缓存它NSURLCache:

- (void)startLoading
{   
    //Could this be why my responses never come out of the cache?
    NSURLResponse *response =[[NSURLResponse alloc]initWithURL:self.request.URL
                                                      MIMEType:nil expectedContentLength:-1
                                              textEncodingName:nil];

    //Get the locally stored data for this request
    NSData* data = [[ELALocalPathSubstitutionService singleton] getLocallyStoredDataForRequest:self.request];

    //Tell the connection to cache the response
    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];

    //Have the connection load the data we just fetched
    [[self client] URLProtocol:self didLoadData:data];

    //Tell the connection to finish up
    [[self client] URLProtocolDidFinishLoading:self];
}
Run Code Online (Sandbox Code Playgroud)

我限制了本地数据被提取到一个的次数.第一次获取它的意图来自于它 …

objective-c nsurlcache nsurlprotocol ios

2
推荐指数
1
解决办法
1856
查看次数

如何使用 Alamofire 完全禁用 URLCache

在 Swift 中使用 Xcode 7.3 iOS 9.2 没有任何可怕的 Objective C 我已经研究了一段时间并且现在已经在这个街区周围三遍了。我在这里尝试过这篇文章,但没有奏效 http://www.mzan.com/article/32199494-alamofire-how-remove-cache.shtml

我也尝试使用苹果文档,但这太糟糕了,我无法理解 if。

所以我正在做的是对我的服务器进行两次 Alamofire 调用。一是测试登录信息的凭据,看输入是否正确。二是下载并返回客户信息以供查看。当我第一次调用它时,两者都工作正常。问题是当我退出应用程序时,我会清除页面中的所有用户信息。但是当我在同一个会话中登录时,它会调用第一个正确的,所以如果我输入了错误的用户名或密码,即使我第一次登录正确,它也会返回 false。但是当我下载客户数据时,它一直在下载我第一次访问用户信息时的旧信息。它使用新的用户名和密码,但仍然下载旧的东西。

这是我的登录和注销功能:

//MARK: ButtonControllers
@IBAction func onLoginClick(sender: AnyObject) {

    errorMessageUI.text = "Checking Creditials"
    email = userNameInput.text!
    password = passwordInput.text!
    buildLoginUrl = checkLoginUrl + emailTag + email + passwordTag + password
    print(buildLoginUrl)
    print("Login Cred")
    checkLoginCredentials(buildLoginUrl)
}

@IBAction func onLogoutClick(sender: AnyObject) {

    //null out everything for logout
    email = ""
    password = ""
    self.loginInformation.setObject(self.email, forKey: "email")
    self.loginInformation.setObject(self.password, forKey: "password")
    self.loginInformation.synchronize()
    performSegueWithIdentifier("logoutSegue", sender: self)
    //self.view = …
Run Code Online (Sandbox Code Playgroud)

nsurlcache ios nsurlsession swift alamofire

2
推荐指数
1
解决办法
6417
查看次数

NSURLSession不使用缓存的响应

当我NSURLCache直接查询时,我能够看到缓存的响应,但是当我通过NSURLSession:dataTaskWithRequest它请求相同的资源时,它总是查询服务器并且永远不会给我缓存的响应,即使禁用了互联网.

我配置NSURLCacheapplication:didFinishLaunchingWithOptions是这样的:

let URLCache = NSURLCache(memoryCapacity: 20 * 1024 * 1024,
                          diskCapacity: 80 * 1024 * 1024, diskPath: nil)
NSURLCache.setSharedURLCache(URLCache)
Run Code Online (Sandbox Code Playgroud)

然后我使用此代码检查缓存并获取响应:

print("cached response is \(NSURLCache.sharedURLCache().cachedResponseForRequest(request)?.response)")

NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
  print("nsurlsession response \(response)")
}.resume()
Run Code Online (Sandbox Code Playgroud)

我的调试打印结果是:

cached response is Optional(<NSHTTPURLResponse: 0x7f809d0ddfe0> { URL: https://api.test.com/stuff } { status code: 200, headers {
"Cache-Control" = "public, s-maxage=600";
Connection = "keep-alive";
"Content-Type" = "application/json";
Date = "Tue, 06 Sep 2016 23:41:24 GMT";
Etag = "\"4800a836fee27c56a3cce1f0f2bddaefa5a7785b\""; …
Run Code Online (Sandbox Code Playgroud)

nsurlcache ios nsurlsession

2
推荐指数
1
解决办法
1774
查看次数

如何使用NSURLSession来确定资源是否已更改?

我正在使用NSURLSession从HTTP服务器请求JSON资源.服务器使用Cache-Control来限制资源缓存在客户端上的时间.

这很好用,但是我还想在内存中缓存一个反序列化的JSON对象,因为它经常被访问,同时继续利用NSURLSession中内置的HTTP缓存机制.

我想我可以保存一些HTTP响应头:Content-MD5,Etag以及Last-Modified反序列化的JSON对象(我使用这3个字段,因为我注意到并非所有HTTP服务器都返回Content-MD5,否则它本身就足够了) .下次我收到JSON对象的响应时,如果这3个字段相同,那么我可以重用以前反序列化的JSON对象.

这是一种确定deserizlied JSON仍然有效的可靠方法.如果没有,我如何确定反序列化的对象是否是最新的?

http-headers nsurlcache ios nshttpurlresponse nsurlsession

1
推荐指数
1
解决办法
4046
查看次数

如何清除URLSession / URLConfiguration存储的缓存数据?

我正在使用以下代码通过URLConfiguration设置URLSession的缓存策略。

if appDelegateObj.configuration == nil {
            appDelegateObj.configuration = URLSessionConfiguration.default
   }

if self.apiType == ServerRequest.API_TYPES_NAME.API1  {


    if appDelegateObj.forceReload == true {
        appDelegateObj.configuration?.urlCache = nil
        appDelegateObj.configuration?.requestCachePolicy = .reloadIgnoringLocalCacheData

    }else{
        appDelegateObj.configuration?.requestCachePolicy = .returnCacheDataElseLoad
    }


}else{
    appDelegateObj.configuration?.requestCachePolicy = .reloadIgnoringLocalCacheData
}
session = URLSession(configuration: appDelegateObj.configuration!, delegate: nil, delegateQueue: nil)
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,即使设置了

appDelegateObj.configuration?.urlCache = nil
Run Code Online (Sandbox Code Playgroud)

我能够获取新数据的唯一方法是通过使用

appDelegateObj.configuration?.requestCachePolicy = .reloadIgnoringLocalCacheData
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么 ?我需要一种方法来清除该应用程序的所有缓存数据。

我尝试使用

URLCache.shared.removeAllCachedResponses()
Run Code Online (Sandbox Code Playgroud)

但这也不起作用。

nsurlcache ios nscache nsurlsession swift

1
推荐指数
1
解决办法
2090
查看次数

URLCache(iOS)。storeCachedResponse异步工作。如何捕捉完成?

刚刚发现函数storeCachedResponse(_ cachedResponse:CachedURLResponse,用于请求:URLRequest)是异步工作的。也就是说,执行后不会立即返回结果。我没有在官方文档中找到对此的描述。参见示例:

cache = URLCache(memoryCapacity: 0, diskCapacity: 100 * 1024 * 1024, diskPath: "myCache")
let config = URLSessionConfiguration.default
config.requestCachePolicy = .returnCacheDataElseLoad
config.urlCache = cache
let session = URLSession(configuration: config)
session.dataTask(with: request, completionHandler: {[unowned self]
    (data, response, error) in

    if let data = data, let response = response, ((response as HTTPURLResponse)?.statusCode ?? 500) < 300 {
        let cachedData = CachedURLResponse(response: response, data: data)                                            
        self.cache.storeCachedResponse(cachedData, for: request)
        let testCachedData = self.cache.cachedResponse(for: request)
    }
}
Run Code Online (Sandbox Code Playgroud)

理论上,testCachedData必须包含缓存的响应。但实际上包含的内容是:

testCachedData?.response.url // Ok
testCachedData?.isEmpty // false
testCachedData?.data …
Run Code Online (Sandbox Code Playgroud)

nsurlcache ios swift

1
推荐指数
1
解决办法
728
查看次数