iOS 网络访问 - NSURLConnection

iOS 网络访问

  • 苹果 API
    • NSURLConnection
      iOS 9.0 之后就会建议使用 NSURLSession "Use NSURLSession (see NSURLSession.h)")
    • NSURLSession(iOS 7.0)
    • CFNetwork(底层实现)
  • 第三方框架
    • AFNetworking
    • ASI
      这个可能很多人已经不用了,因为作者已经不再更新了,但是 ASI 的下载还是很好用的,而且 ASI 是通过 CFNetwork 实现的,首先效率很高,而且底层本来就很稳定,不更新也是很正常的

NSURLConnection

    NSURL *url = [NSURL     NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 需要修改请求头或者请求体的时候,需要的是 mutable URL request
    NSMutableURLRequest *requestM = [[NSMutableURLRequest alloc] initWithURL:url];
    [requestM setValue:@"iPhone AppleWebKit" forHTTPHeaderField:@"User_Agent"];
    
    __weak typeof(self) weakSelf = self;
    // requestM 打开的才是移动端的网页
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil && data.length > 0) {
            NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            [weakSelf.webView loadHTMLString:html baseURL:url];
        }
    }];

代码其实挺简单的,而且 NSURLConnection 已经 9.0 弃用了,如果还有想要尝试的童鞋还是可以看看的,毕竟是苹果最早处理网络访问的方法。
一般 connection 都会异步发送请求,但是也有同步的时候,比如断点续传,下载文件之前需要知道上次下载文件大小,就可以同步发送请求,而且可以发送 HEAD 请求。
HEAD 请求

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/videos.zip"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // HEAD 请求不会返回响应体,只是返回响应头,可以查看数据大小
    request.HTTPMethod = @"HEAD";
    NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
    NSLog(@"HEAD response head -- %zd", response.expectedContentLength);
    NSLog(@"HEAD response body -- %zd", data.length);
P.S.(Postscript)

GET 请求

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/login.php?username=username+&password=pwd"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil && data.length > 0) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            NSLog(@"%@", dict);
        } else {
            NSLog(@"%@", connectionError);
        }
    }];

POST 请求

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/login.php"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 默认是通过 GET 发送请求
    request.HTTPMethod = @"POST";
    NSString *requestBodyString = @"username=username&password=pwd";
    NSData *requestBody = [requestBodyString dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = requestBody;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil && data.length > 0) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            NSLog(@"%@", dict);
        } else {
            NSLog(@"%@", connectionError);
        }
    }];

你可能感兴趣的:(iOS 网络访问 - NSURLConnection)