***************************************************
同步下载
以下方式下载的话,如果文件过大
请求数据
@interface NSURL: NSObject <</span>NSSecureCoding, NSCopying>
+ (id)URLWithString:(NSString *)URLString;
url请求地址(不支持空格和中文,都要进行转码,方法如上)
+ (id)dataWithContentsOfURL:(NSURL *)url;
NSData的+方法
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
NSJSONSerialization 的+方法
获取图片:
+ (id)URLWithString:(NSString *)URLString;
+ (id)dataWithContentsOfURL:(NSURL *)url;
+ (UIImage *)imageWithData:(NSData *)data;
然后就能获取他的url了
***********
使用线程 就可以使用同步下载方法
+ (id)dataWithContentsOfURL:(NSURL *)url;
同步下载方法
__unused NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://dl_dir.qq.com/qqfile/qq/QQforMac/QQ_V2.4.1.dmg"]];
同步下载
如果放到主线程中就会阻塞
放到子线程中就没关系
**************************************,*
异步下载
其实就是封装的多线程
(网络一定都要用异步, 不能用同步)
请求:
封装url
响应:
响应头
statusCode :404(4开头的都是客户端错误,5开头都是服务端的错误,2开头就是请求成功(一般是200),3开头就是跳转) 状态码
Content-Type: image/png
Content-Length:2000 响应体的内容的长度
响应体
二进制数据
’
步骤:
+ (id)URLWithString:(NSString *)URLString;
NSURL
@interface NSURLRequest : NSObject <</span>NSSecureCoding, NSCopying, NSMutableCopying>
+ (id)requestWithURL:(NSURL *)URL;
创建请求
+ (id)requestWithURL:(NSURL *)URL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval;
带缓存的request
enum
{
};
typedef NSUInteger NSURLRequestCachePolicy;
几种缓存方式
typedef double NSTimeInterval;
超时时间
@interface NSURLConnection : NSObject
+ (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;
发送请求
@protocol
NSURLConnectionDataDeleg
写协议方法(4个)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
要先强转成http响应才行
@interface NSHTTPURLResponse
: NSURLResponse
http协议的效应
- (NSDictionary *)allHeaderFields;
http响应的响应头
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
每次下一点
- (void)appendData:(NSData *)other;
用这个方法拼接数据
缓存机制
- (void)connectionDidFinishLoadi
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
异步下载图片可以用第三方库