网络连接相关类

NSURLConnection:支持ftp://,http://,https://,file:///(本地文件)连接

发送同步连接请求,该函数会阻塞,直到有响应返回

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error

异步连接请求,执行该函数后就立即开始连接;一般来说都在主线程中调用该函数;若在新线程中调用,则回调函数不会被执行,需通过scheduleInRunLoop使回调生效

+ (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate

在其他线程中使异步连接的回调生效

- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode

- (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode

一般情况下,我们使用NSURLConnection时,都使用如下的代码:

_connection = [[NSURLConnection alloc] initWithRequest:URLRequest delegate:self];

这段代码创建的connection运行在main runloop以及NSEventTrackingRunLoopMode下,而该模式在mouse-dragging loops and other sorts of user interface tracking loops期间会阻止对该connection的代理通知事件,比如在UITableView滚动的时候,connection的代理方法就不会被通知。这不是我们想要的,如果想要在mouse-dragging loops and other sorts of user interface tracking loops期间我们的connection的代理方法仍然被调用,可用以下代码替换上面的代码:

_connection = [[NSURLConnection alloc] initWithRequest:URLRequest delegate:self startImmediately:NO];

[_connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];

[_connection start];

NSURLRequest:url请求,包括一系列获取属性值方法,不能设置,要设置只能使用NSMutableURLRequest

初始化一个请求,第一个构造函数等同于第二个构造函数的缓存策略参数为NSURLRequestUseProtocolCachePolicy,超时时间60秒

+ (id)requestWithURL:(NSURL *)theURL

+ (id)requestWithURL:(NSURL *)theURL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval

NSMutableURLRequest:NSURLRequest子类,实际上该类就是提供了NSURLRequest所有属性的设置方法

常用设置函数:

- (void)setHTTPBody:(NSData *)data

- (void)setHTTPMethod:(NSString *)method    默认是GET

- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field

- (void)addValue:(NSString *)value forHTTPHeaderField:(NSString *)field  与setValue的不同:若已存在一个键值,则附加新值到旧值的后面,以逗号分隔

NSURLResponse:

- (NSString *)suggestedFilename 返回网络数据需要保存的文件名

NSHTTPURLResponse:NSURLResponse的子类

- (NSDictionary *)allHeaderFields  获取HTTP服务器返回的头信息

- (NSInteger)statusCode 获取状态码

+ (NSString *)localizedStringForStatusCode:(NSInteger)statusCode 根据状态码获取本地化文本内容,比如状态码200表示无错误

NSURL:

- (NSString *)absoluteString  获取url的字符串

- (NSString *)query 获取url中问号后面跟的参数字符串

你可能感兴趣的:(网络连接相关类)