奇怪的NSURLConnection缓存行为

时间:2013-07-27 08:07:42

标签: ios objective-c nsurlconnection nsurlrequest nsurlcache

我有一个简单的方法,它接受一个url并从服务器加载它:

- (void)loadURL:(NSString*)url
{
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
    request.HTTPMethod = @"GET";
    request.URL = [NSURL URLWithString:url];

    NSHTTPURLResponse* response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
}

服务器返回max-age为1天的响应。

问题是当我重复运行这3行时,其中2行随机错过缓存并重新加载响应:

[self loadURL:@"http://192.168.0.105:8080/users/51bdbc73808897302f000001/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09RoyipmXgcENwfE6EV9yzvgp5VTSZww"];
[self loadURL:@"http://192.168.0.105:8080/users/51ee9d4e263d08fe04000003/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09RoyipmXgcENwfE6EV9yzvgp5VTSZww"];
[self loadURL:@"http://192.168.0.105:8080/users/51d17b81de38c60b20000006/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09RoyipmXgcENwfE6EV9yzvgp5VTSZww"];

如果我向每个请求的查询字符串添加一些随机唯一数据(& x,& y和& z),它就可以解决问题:

[self loadURL:@"http://192.168.0.105:8080/users/51bdbc73808897302f000001/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09RoyipmXgcENwfE6EV9yzvgp5VTSZww&x"];
[self loadURL:@"http://192.168.0.105:8080/users/51ee9d4e263d08fe04000003/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09RoyipmXgcENwfE6EV9yzvgp5VTSZww&y"];
[self loadURL:@"http://192.168.0.105:8080/users/51d17b81de38c60b20000006/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09RoyipmXgcENwfE6EV9yzvgp5VTSZww&z"];

另外,如果我将查询字符串的长度减少到80个字符,它也可以解决问题:

[self loadURL:@"http://192.168.0.105:8080/users/51bdbc73808897302f000001/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09Royipm"];
[self loadURL:@"http://192.168.0.105:8080/users/51ee9d4e263d08fe04000003/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09Royipm"];
[self loadURL:@"http://192.168.0.105:8080/users/51d17b81de38c60b20000006/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09Royipm"];

发生了什么事? 这是iOS中的错误吗?我该如何解决?

P.S:我在一个空的应用程序中对此进行了测试,在iOS 5和6上都没有额外的东西。

2 个答案:

答案 0 :(得分:0)

使用NSURLRequestrequestWithURL:cachePolicy:timeoutInterval:中设置缓存行为。尝试:

- (void)loadURL:(NSString*)url
{
    NSURL *url = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];

    NSHTTPURLResponse* response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
}

可能还会NSURLRequestReloadIgnoringLocalAndRemoteCacheData使用cachePolicy

答案 1 :(得分:0)

您可能希望使用ASIHTTPRequest http://allseeing-i.com/ASIHTTPRequest/