iOS中的NSURLCache数据缓存类用法解析

2020-01-15 15:06:41于丽

  
    NSURLConnection *newConnection = [[NSURLConnection alloc] initWithRequest:self.request
                                                                     delegate:self
                                                             startImmediately:YES];
    self.connection = newConnection;
}

使用下面代码,我将请求的过程打印出来
- (void)  connection:(NSURLConnection *)connection
  didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"将接收输出");
}
- (NSURLRequest *)connection:(NSURLConnection *)connection
             willSendRequest:(NSURLRequest *)request
            redirectResponse:(NSURLResponse *)redirectResponse{
    NSLog(@"即将发送请求");
    return(request);
}
- (void)connection:(NSURLConnection *)connection
    didReceiveData:(NSData *)data{
    NSLog(@"接受数据");
    NSLog(@"数据长度为 = %lu", (unsigned long)[data length]);
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse *)cachedResponse{
    NSLog(@"将缓存输出");
    return(cachedResponse);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"请求完成");
}
- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error{
    NSLog(@"请求失败");
}

@end

第一次打印结果如下
 


2013-01-31 15:28:29.923 NSURLCacheDemo[27848:907] 即将发送请求
2013-01-31 15:28:30.043 NSURLCacheDemo[27848:907] 将接收输出
2013-01-31 15:28:30.045 NSURLCacheDemo[27848:907] 接受数据
2013-01-31 15:28:30.047 NSURLCacheDemo[27848:907] 数据长度为 = 30047
2013-01-31 15:28:30.095 NSURLCacheDemo[27848:907] 接受数据
2013-01-31 15:28:30.098 NSURLCacheDemo[27848:907] 数据长度为 = 3575
2013-01-31 15:28:30.102 NSURLCacheDemo[27848:907] 接受数据
2013-01-31 15:28:30.104 NSURLCacheDemo[27848:907] 数据长度为 = 1482
2013-01-31 15:28:30.105 NSURLCacheDemo[27848:907] 将缓存输出
2013-01-31 15:28:30.107 NSURLCacheDemo[27848:907] 请求完成