概述
iOS中網絡數據請求。
主要涉及的類
- NSURLRequest
- NSURLSession
- NSURLSessionDataTask
- NSURLSessionConfiguration
本文只是一個簡單的展示get和post請求的示例,將基本的操作包含其中。
如果想要深入瞭解如何配置網絡請求框架還需要了解網絡部分的相關知識,iOS中都有相應的api。
配置http可以使用
iOS 9.0由於強制使用https , 所以之前使用的 http的連接 的應用如果不做特殊配製就都不可以運行了,爲了解決這個問題要在工程的info.plit中添加如下配製。
示例
簡單的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