NSURL

 
让我们先看一下URL的结构:
protocol://username:hostname:port/pathname[?query][#fragment]
查询与pathname之间用 ?分隔,参数间使用&分隔
例如:
http://root:Password1@example.com:8042/over/there/index.dtb?type=animal&name=narwhal#nose
 
构建NSURL:
NSURL *baseURL = [NSURL URLWithString:@"file:///path/to/web_root/"];
NSURL *url = [NSURL URLWithString:@"folder/file.html" relativeToURL:baseURL];
NSURL *absURL = [url absoluteURL];
NSLog(@"absURL = %@", absURL);
 
NSURL *url = [[NSURL alloc]initWithScheme:@"http"
                                     host:@"www.baidu.com"

                                     path:@"/index.html”];

 

NSURL请求缓存:

当一个请求完成下载来自服务器的回应,一个缓存的回应将在本地保存。下一次同一个请求再发起时,本地保存的回应就会马上返回,不需要连接服务器。NSURLCache 会 自动 且 透明 地返回回应。

 

NSURLCache类:

NSURLCache为URL请求提供了内存中以及磁盘上的综合缓存机制。

任何通过NSURLConnection加载的请求都将被NSURLCache处理。

为了好好利用NSURLCache,你需要初始化并设置一个共享的URL缓存。

在didiFinishLaunchingWithOptions:中加入

NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024

     diskCapacity:20 * 1024 * 1024

diskPath:nil];

 

NSURLRequestCachePolicy

NSURLRequest有个cachePolicy属性,指定了请求的缓存行为。其值如下:

 NSURLRequestUseProtocolCachePolicy                 默认行为,使用网络协议中实现的缓存协议

ReloadIgnoringLocalCacheData           不使用缓存

ReturnCahcheDataElseLoad                 使用缓存(不管它是否过期),如果缓存中没有,则从网络加载

ReturnCacheDataDontLoad              离线模式:使用缓存(不管它是否过期),但是不从网络加载   

 

NSURLConnectionDelegate中

 - (NSCachedURLResponse *)connection:(NSURLConnection *)connection

                  willCacheResponse:(NSCachedURLResponse *)cachedResponse

{

    NSMutableDictionary *mutableUserInfo = [[cachedResponse userInfo] mutableCopy];

    NSMutableData *mutableData = [[cachedResponse data] mutableCopy];

    NSURLCacheStoragePolicy storagePolicy = NSURLCacheStorageAllowedInMemoryOnly;

 

    // ...

 

    return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response]

                                                    data:mutableData

                                                userInfo:mutableUserInfo

                                           storagePolicy:storagePolicy];

}

 NSCachedURLResponse 是个包含 NSURLResponse 以及它对应的缓存中的 NSData 的类

如果 -connection:willCacheResponse: 返回 nil,回应将不会缓存。

如果不实现此方法,NSURLConnection 就简单地使用本来要传入 -connection:willCacheResponse: 的那个缓存对象,所以除非你需要改变一些值或者阻止缓存,否则这个代理方法不必实现。

 

 

 

 

posted @ 2015-08-06 15:08  LaiSong  阅读(321)  评论(0编辑  收藏  举报