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 = [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 = 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 = data; NSLog(@"%ld", (unsigned long)loginData.length);}];
此方法會建立一個新的線程用於接受網路端返回資料,傳回值為void,當資料接受完畢後會執行block中的語句;