IOS-網絡(HTTP請求、同步請求、異步請求、JSON解析數據)


 

  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 *)request
121 {
122     //發送用戶名和密碼給服務器(HTTP協議)
123     NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
124     /*
125      JSON
126      1>JSON是一種輕量級的數據格式,一般用於數據交互
127      服務器返回給客戶端的數據一般都是JSON格式或者XML格式
128      標准的JSON合適注意點:key必須用雙引號
129      
130      2>要想從JSON中挖出具體數據得對JSON進行解析
131      JSON           OC
132      {}-----------NSDictonary
133      []-----------NSArray
134      " "-----------NSString
135      數字-----------NSNumber
136      
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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM