// // ZFViewController.m // 0628-表單驗證 // // #import "ZFViewController.h" #import "MBProgressHUD+MJ.h" @interface ZFViewController () @property (weak, nonatomic) IBOutlet UITextField *userNameTextField; @property (weak, nonatomic) IBOutlet UITextField *passWordTextField; @end @implementation ZFViewController - (void)viewDidLoad { [super viewDidLoad]; } - (IBAction)login:(id)sender { //驗證賬號和密碼是否合法 if (self.userNameTextField.text.length == 0) { [MBProgressHUD showError:@"請輸入賬號"]; return; } if (self.passWordTextField.text.length == 0) { [MBProgressHUD showError:@"請輸入密碼"]; return; } //取出賬號和密碼 NSString *userName = self.userNameTextField.text; NSString *password = self.passWordTextField.text; //生成URL NSString *urlPath = [NSString stringWithFormat:@"http://192.168.1.101:8080/ZFServer/login?username=%@&pwd=%@", userName, password]; NSURL *url = [NSURL URLWithString:urlPath]; //生成連接 NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url]; //建立連接並接收返回數據(同步執行) // NSData *loginData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil]; //建立連接並接收返回數據(異步執行) NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSData *loginData = data; NSLog(@"%ld", (unsigned long)loginData.length); }]; //打印返回的數據長度 NSLog(@"%@", self.userNameTextField.text); NSLog(@"%@", self.passWordTextField.text); // NSLog(@"%ld", (unsigned long)loginData.length); } @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 = data; NSLog(@"%ld", (unsigned long)loginData.length); }];
此方法會建立一個新的線程用於接受網絡端返回數據,返回值為void,當數據接受完畢後會執行block中的語句;