NSURLConnection的基本使用

虽然在实际项目开发中,我们最经常使用的网络请求三方框架是AFNetworking,很多程序员不知道NSURLConnection而只知道AFNetworking,这就会带来很多局限性,NSURLConnection虽然在iOS9以后就被废弃了,可是作为apple的系统API,对于我们理解网络请求是非常有帮助的,首先我们来看下实例化api:

- (nullable instancetype)initWithRequest:(NSURLRequest *)request delegate:(nullable id)delegate startImmediately:(BOOL)startImmediately API_DEPRECATED("Use NSURLSession (see NSURLSession.h)", macos(10.5,10.11), ios(2.0,9.0), tvos(9.0,9.0)) __WATCHOS_PROHIBITED;

- (nullable instancetype)initWithRequest:(NSURLRequest *)request delegate:(nullable id)delegate API_DEPRECATED("Use NSURLSession (see NSURLSession.h)", macos(10.3,10.11), ios(2.0,9.0), tvos(9.0,9.0)) __WATCHOS_PROHIBITED;
+ (nullable NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(nullable id)delegate API_DEPRECATED("Use NSURLSession (see NSURLSession.h)", macos(10.3,10.11), ios(2.0,9.0), tvos(9.0,9.0)) __WATCHOS_PROHIBITED;

三种实例化方法,都是在delegate里面接受数据,GET/POST请求在NSMutableURLRequest里面进行

//接收到响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    
}

//接收到服务器返回的data
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
}

//connection请求完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
}

另外还有2个更简洁的方法,直接在block里面进行数据接受:

//1.异步请求
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            //接受数据转json操作等等。。。
                               dispatch_async(dispatch_get_main_queue(), ^{
                                  //刷新UI操作
                               });
                           }];
    //2.同步请求
    //响应
    NSURLResponse *response = [[NSURLResponse alloc]init];
    NSError *error;
    //接受服务器返回的数据
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request
                                                 returningResponse:&response
                                                             error:&error];
    //转json
    id json = [NSJSONSerialization JSONObjectWithData:responseData
                                              options:kNilOptions
                                                error:nil];

这里要注意一下,接收到数据以后,UI方面的刷新都必须保证在主线程进行。

你可能感兴趣的:(NSURLConnection的基本使用)