cachedResponseForRequest

cachedResponseForRequest

在Xcode 4.4中不会发生这种情况,但在使用iOS6模拟器或真实设备的4.5中,如果从cachedResponseForRequest内部调用sendSynchronousRequest,则直到超时之前,对sendSynchronousRequest的调用不会返回。

同样,使用sendAsynchronousRequest并循环旋转(每10秒检查一次10秒是否完成)的循环,完成循环(经过10秒),但从不完成请求(如果从cachedResponseForRequest内部调用)。

在Xcode 4.4(模拟ios5)中,不会发生这种情况。
有任何想法吗?

最佳答案

只需使用方法“sendAsynchronousRequest”。
这是我的解决方案,它就像一种魅力。

[NSURLConnection sendAsynchronousRequest:newRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data,NSError *error){
        NSLog(@"--- caching ---");
        if (error) {
            NSLog(@"%@", error);
            NSLog(@"not cached: %@", absoluteString);
        }
        NSString *filename = [self sha1:absoluteString];
        NSString *path = [cacheDirectory stringByAppendingPathComponent:filename];
        NSFileManager *fileManager = [[NSFileManager alloc] init];
        [fileManager createFileAtPath:path contents:data attributes:nil];
        [fileManager release];

        NSURLResponse *newResponse = [[NSURLResponse alloc] initWithURL:response.URL MIMEType:response.MIMEType expectedContentLength:data.length textEncodingName:nil];

        NSDictionary *responseInfo = [NSDictionary dictionaryWithObjectsAndKeys:filename, @"filename", newResponse.MIMEType, @"MIMEType", nil];
        [responsesInfo setObject:responseInfo forKey:absoluteString];
        cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:newResponse data:data];
        [newResponse release];
        [cachedResponses setObject:cachedResponse forKey:absoluteString];
        [cachedResponse release];
    }];

因为它仅在iOS5.0和更高版本中可用。您可能需要先检查ios版本。

关于ios - ios6 cachedResponseForRequest块sendSynchronousRequest,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12920165/

10-13 04:03