首页 > 代码库 > iOS网络编程--NSConnection的同步连接与异步连接

iOS网络编程--NSConnection的同步连接与异步连接

 1 // 2 //  ZFViewController.m 3 //  0628-表单验证 4 // 5 //  Created by zfan on 14-6-28. 6 //  Copyright (c) 2014年 zfan. All rights reserved. 7 // 8  9 #import "ZFViewController.h"10 #import "MBProgressHUD+MJ.h"11 12 @interface ZFViewController ()13 14 @property (weak, nonatomic) IBOutlet UITextField *userNameTextField;15 @property (weak, nonatomic) IBOutlet UITextField *passWordTextField;16 17 @end18 19 @implementation ZFViewController20 21 - (void)viewDidLoad22 {23     [super viewDidLoad];24 }25 26 - (IBAction)login:(id)sender27 {28     //验证账号和密码是否合法29     if (self.userNameTextField.text.length == 0)30     {31         [MBProgressHUD showError:@"请输入账号"];32         return;33     }34     35     if (self.passWordTextField.text.length == 0)36     {37         [MBProgressHUD showError:@"请输入密码"];38         return;39     }40     41     //取出账号和密码42     NSString *userName = self.userNameTextField.text;43     NSString *password = self.passWordTextField.text;44     45     //生成URL46     NSString *urlPath = [NSString stringWithFormat:@"http://192.168.1.101:8080/ZFServer/login?username=%@&pwd=%@", userName, password];47     NSURL *url = [NSURL URLWithString:urlPath];48     49     //生成连接50     NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];51     52     //建立连接并接收返回数据(同步执行)53 //    NSData *loginData = http://www.mamicode.com/[NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];>54     55     56     //建立连接并接收返回数据(异步执行)57     NSOperationQueue *queue = [[NSOperationQueue alloc] init];58     [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {59         NSData *loginData =http://www.mamicode.com/ data;60         NSLog(@"%ld", (unsigned long)loginData.length);61     }];62     63     //打印返回的数据长度64     NSLog(@"%@", self.userNameTextField.text);65     NSLog(@"%@", self.passWordTextField.text);66 //    NSLog(@"%ld", (unsigned long)loginData.length);67 }68 69 @end

知识要点:

1>通过NSString类方法拼接字符串,生成完整的URL路径;

2>通过NSURLRequest的类方法,利用URL建立一个NSURLRequest连接实例;

3>通过NSConnection的类方法建立连接并接受返回数据,可通过同步方式和异步方式实现:

 

  3.1>同步方式

[NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];

  此方法不会新建线程,返回值为NSData,由于未新建线程,因此在该方法未完成前,线程不会继续向下运行,容易造成卡死;

 

  3.2>异步方式

NSOperationQueue *queue = [[NSOperationQueue alloc] init];[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {  NSData *loginData =http://www.mamicode.com/ data;  NSLog(@"%ld", (unsigned long)loginData.length);}];

  此方法会建立一个新的线程用于接受网络端返回数据,返回值为void,当数据接受完毕后会执行block中的语句;