IOS - 網路(HTTP請求、同步請求、非同步請求、JSON解析資料)

來源:互聯網
上載者:User

標籤:

 

  1 //  2 //  ViewController.m  3 //  IOS_0129_HTTP請求  4 //  5 //  Created by ma c on 16/1/29.  6 //  Copyright © 2016年 博文科技. All rights reserved.  7 //  8   9 #import "ViewController.h" 10 #import "MBProgressHUD+MJ.h" 11  12 @interface ViewController () 13 @property (weak, nonatomic) IBOutlet UITextField *textName; 14 @property (weak, nonatomic) IBOutlet UITextField *textPassword; 15  16 - (IBAction)btnlogin; 17  18 @end 19  20 @implementation ViewController 21 /* 22  1.常見的發送HTTP請求的方案: 23  1>蘋果原生內建的 24    NSURLConnection:用法簡單,最經典,最直接 25    NSURLSession:功能比NSURLConnection強大 26    CFNetwork:NSURL底層,純C語言 27  2>第三方架構 28    ASIHttpRequest:“HTTP終結者”,功能及其強大,可惜停止更新 29    AFNetWorking:簡單易用,提供基本夠用的常用功能,維護者多 30    MKNetWorkKit:簡單易用,維護者使用者少 31  3>建議 32    為了提高開發效率,企業開發用的基本是第三方架構 33   34  2.常用類 35  1>NSURL:請求地址 36  2>NSURLRequest:一個NSURLRequest對象代表一個請求 - 包含資訊有: 37    a.一個NSURL對象 38    b.要求方法、要求標頭、請求體 39    c.請求逾時 40  3>NSMutableURLRequest: 41  4>NSURLConnection - 負責發送請求,建立用戶端與伺服器的串連 42    發送NSURLRequest的資料給伺服器,並收來自伺服器響應的資料 43   44  3.NSURLConnection使用步驟: 45    1>建立NSURL對象,並佈建要求路徑 46    2>傳入一個NSURL對象建立NSURLRequest對象,佈建要求頭和請求體 47    3>使用NSURLConnection發送NSURLRequest 48  */ 49  50 - (void)viewDidLoad { 51     [super viewDidLoad]; 52      53     self.view.backgroundColor = [UIColor groupTableViewBackgroundColor]; 54 } 55 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 56 { 57     [self.view endEditing:YES]; 58 } 59  60  61 - (IBAction)btnlogin { 62      63     NSString *usernameText = self.textName.text; 64     if (usernameText.length == 0) { 65         [MBProgressHUD showError:@"請輸入帳號"]; 66         return; 67     } 68     self.textPassword.secureTextEntry = YES; 69     NSString *password = self.textPassword.text; 70     if (password.length == 0) { 71         [MBProgressHUD showError:@"請輸入密碼"]; 72         return; 73     } 74     NSLog(@"發送資料給伺服器"); 75      76     /* 77      介面文檔:定義描述伺服器端的請求介面 78      1>請求路徑URL:用戶端應該請求哪個路徑 79      2>請求參數:用戶端要發給伺服器的資料 80      3>請求結果:伺服器要返回什麼給用戶端 81      */ 82      83     //建立一個NSURL:請求路徑 84     NSString *strURL = [NSString stringWithFormat:@"http://localhost:8080/MJServer/login?username=%@&pwd=%@",usernameText,password]; 85     NSURL *url = [NSURL URLWithString:strURL]; 86     //建立一個請求 87     NSURLRequest *request = [NSURLRequest requestWithURL:url]; 88  89     //同步請求 90     [self sendSyncWithRequest:request]; 91     //非同步請求 92     [self sendAsyncWithRequest:request]; 93      94 } 95 //非同步請求 96 - (void)sendAsyncWithRequest:(NSURLRequest *)request 97 { 98     NSOperationQueue *queue = [NSOperationQueue mainQueue]; 99     100     [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {101         //這個block會在請求完畢的時候自動調用102         if (connectionError || data == nil) {103             [MBProgressHUD showError:@"請求失敗"];104             return;105         }106         //解析伺服器返回的JSON資料107         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];108         NSString *error = dict[@"error"];109         if (error) {110             [MBProgressHUD showError:error];111         }112         else{113             NSString *success = dict[@"success"];114             [MBProgressHUD showSuccess:success];115         }116     }];117 }118 119 //同步請求120 - (void)sendSyncWithRequest:(NSURLRequest *)request121 {122     //發送使用者名稱和密碼給伺服器(HTTP協議)123     NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];124     /*125      JSON126      1>JSON是一種輕量級的資料格式,一般用於資料互動127      伺服器返回給用戶端的資料一般都是JSON格式或者XML格式128      標準的JSON合適注意點:key必須用雙引號129      130      2>要想從JSON中挖出具體資料得對JSON進行解析131      JSON           OC132      {}-----------NSDictonary133      []-----------NSArray134      " "-----------NSString135      數字-----------NSNumber136      137      3>JSON解析方案138      第三方架構:JSONKit、SBJson、TouchJSON(效能從左至右,越差)139      蘋果原生(內建):NSJSONSerialization(效能最好)140      4>JSON資料轉-->OC對象141      + (nullable id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;142      5>OC對象-->JSON資料143      + (nullable NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;144      */145     //解析伺服器返回的JSON資料146     NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];147     NSString *error = dict[@"error"];148     if (error) {149         [MBProgressHUD showError:error];150     }151     else{152         NSString *success = dict[@"success"];153         [MBProgressHUD showSuccess:success];154     }155     156 }157 @end

 

IOS - 網路(HTTP請求、同步請求、非同步請求、JSON解析資料)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.