天天看點

iOS入門-37NSURLSession網絡資料請求概述示例

概述

iOS中網絡資料請求。

主要涉及的類

  • NSURLRequest
  • NSURLSession
  • NSURLSessionDataTask
  • NSURLSessionConfiguration

本文隻是一個簡單的展示get和post請求的示例,将基本的操作包含其中。

如果想要深入了解如何配置網絡請求架構還需要了解網絡部分的相關知識,iOS中都有相應的api。

配置http可以使用

iOS 9.0由于強制使用https , 是以之前使用的 http的連接配接 的應用如果不做特殊配制就都不可以運作了,為了解決這個問題要在工程的info.plit中添加如下配制。

iOS入門-37NSURLSession網絡資料請求概述示例

示例

簡單的get和post請求,點選兩個按鈕進行相應的請求。

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //建立倆按鈕,點選分别進行get請求,post請求
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    btn.frame = CGRectMake(50, 50, 80,40);
    
    [btn setTitle:@"GET請求" forState:UIControlStateNormal];
    
    [btn addTarget:self action:@selector(loadDataByGet) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton* btn01 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    btn01.frame = CGRectMake(50, 150, 80, 40);
    
    [btn01 setTitle:@"POST請求" forState:UIControlStateNormal];
    
    [btn01 addTarget:self action:@selector(loadDataByPost) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btn];
    
    [self.view addSubview:btn01];
}

-(void)loadDataByGet{
    //字元串網址(可能包含get請求需要的參數)
    NSString* urlStr = @"你的請求url";
    //将字元串網址轉化為一個位址連接配接對象
    NSURL* url = [NSURL URLWithString:urlStr];
    //建立一個連接配接請求對象
    //裡面封裝了請求資訊,發向目的位址
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    //建立會話對象
    NSURLSession* session = [NSURLSession sharedSession];
    //建立回話任務對象
    //分兩種方法
    //方法一:
    //p1:請求對象
    //p2:完成之後處理函數。其中包含了,data:響應體資料(我們要的json);response:響應頭資訊;error:請求失敗的話,錯誤資訊
//    NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//
//    NSLog(@"dicRoot==%@",dicRoot);
//
//    NSLog(@"response==%@",response);
//
//    NSLog(@"error==%@",error);
//    }];
    
    //方法二
    //該方法内部會自動将請求路徑包裝成一個請求對象,該請求對象預設包含了請求頭資訊和請求方法(GET)
    //如果要發送的是POST請求,則不能使用該方法
    NSURLSessionDataTask* dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        //json解析根字典
        NSDictionary* dicRoot = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        //列印傳回資料
        
        NSLog(@"dicRoot==%@",dicRoot);
        
        NSLog(@"response==%@",response);
        
        NSLog(@"error==%@",error);
        
    }];
    
    //執行
    [dataTask resume];
    
}

-(void) loadDataByPost {
    //字元串網址
    NSString* urlStr = @"你的請求url";
    //将字元串網址轉化為一個位址連接配接對象
    NSURL* url = [NSURL URLWithString:urlStr];
    //請求對象
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    
    //post請求,參數添加到請求體中
    request.HTTPMethod = @"POST";
    //post請求三個參數,name和age和jf
    NSString *name = @"lilei";
    NSString *age = @"12";
    NSString *jf = @"1";
    NSString *bodyDataString = [NSString stringWithFormat:@"name=%@&age=%@&jf=%@", name, age,jf];
    //建立請求體對象并指派;請求體對象使用的是UTF8編碼
    request.HTTPBody = [bodyDataString dataUsingEncoding:NSUTF8StringEncoding];
    
    //初始化會話配置對象
    NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
    //配置請求頭(一些統一配置的參數放頭裡):系統為iOS,傳回資料要求json
    config.HTTPAdditionalHeaders = @{
    @"os"       : @"iOS",
    @"Content-Type"  : @"application/json"
    };
    //建立會話對象
    //p1:會話配置對像
    NSURLSession* session = [NSURLSession sessionWithConfiguration:config];
    //建立會話任務
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        //列印傳回資料
        //json解析根字典
         NSDictionary* dicRoot = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSLog(@"dicRoot==%@",dicRoot);
        
        NSLog(@"response==%@",response);
        
        NSLog(@"error==%@",error);
    }];
    
    [task resume];
}

@end