本人就iOS開發(fā)中常見的網絡數(shù)據(jù)解析方式以及使用情況做了匯總带污,希望閱讀者能夠從中受益.....
為了便于分析忠售,本人就直接搞了一個新聞接口 通過解析并輸出其中數(shù)據(jù)來確保操作正確性他爸,好了 閑話不多說了,咱們就直接進入正題黄虱。
一、準備操作
首先我們修改工程的Info.plist文件 //xcode 7 之后若想要使用HTTP 需要修改info.plist文件 這一點大家看圖就會明白
繼而
@interface ViewController ()<NSURLConnectionDataDelegate>//三個代理這里選中DataDelegate
@property(nonatomic,strong)NSMutableArray *dataArray;//存放解析完成數(shù)據(jù)的數(shù)組
//定以一個可變data 數(shù)據(jù)
@property(nonatomic,strong)NSMutableData *tempData;
@end
//新聞接口
#define BASE_URL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
//將上面的字符串分段為以 ? 為分界線分為兩部分
#define URL_POST1 @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"
#define URL_POST2 @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
//懶加載初始化數(shù)組
-(NSMutableArray *)dataArray{
if (_dataArray == nil) {
_dataArray =[NSMutableArray array];
}
return _dataArray;
}
二蹬癌、網絡數(shù)據(jù)解析方式和用法
1、Get同步解析
- (IBAction)getTongbu:(UIButton *)sender {
NSLog(@"=============Get同步");
//創(chuàng)建url對象
NSURL *url = [NSURL URLWithString:BASE_URL];
//創(chuàng)建請求對象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//設置請求方式 這一步可以不寫 默認設置為get請求
[request setHTTPMethod:@"get"];
//創(chuàng)建相應對象
NSURLResponse *response = nil;
NSError *error;
//創(chuàng)建連接對象
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
// NSLog(@"%@",dict);
NSArray *array =dict[@"news"];
for (NSDictionary *dic in array) {
NewsModel *model =[NewsModel new];
[model setValuesForKeysWithDictionary:dic];
[self.dataArray addObject:model];
}
for (NewsModel *model in _dataArray) {
NSLog(@"%@",model);
}
}
2虹茶、Post同步解析
- (IBAction)postTongbu:(UIButton *)sender {
NSLog(@"=============Post同步");
//創(chuàng)建url對象
NSURL *url = [NSURL URLWithString:URL_POST1];
//創(chuàng)建請求對象
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
//設置請求方式
[request setHTTPMethod:@"post"];//get可以進行省略 但是post不能省略
//設置請求參數(shù)
NSData *tempData =[URL_POST2 dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:tempData];
//創(chuàng)建響應對象
NSURLResponse *responde = nil;
//創(chuàng)建連接對象
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse: &responde error:&error];
NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSArray *arary =dict[@"news"];
for (NSDictionary *dic in arary) {
NewsModel *model =[NewsModel new];
[model setValuesForKeysWithDictionary:dic];
[self.dataArray addObject:model];
}
for (NewsModel *model in _dataArray) {
NSLog(@"%@",model);
}
}
3逝薪、Get異步Block
- (IBAction)getYiBlock:(id)sender {
NSLog(@"=============Get異步Block");
NSURL *url =[NSURL URLWithString:BASE_URL];
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"get"];
__weak typeof(self)temp = self;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSError *error;
NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSArray *array =dict[@"news"];
for (NSDictionary *dic in array) {
NewsModel *model = [NewsModel new];
[model setValuesForKeysWithDictionary:dic];
[temp.dataArray addObject:model];
}
for (NewsModel *model in temp.dataArray) {
NSLog(@"%@",model);
}
}];
}
4、Post異步Block
- (IBAction)postYoBlock:(id)sender {
NSLog(@"=============Post異步Block同步");
NSURL *url = [NSURL URLWithString:URL_POST1];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLResponse *responde = nil;
[request setHTTPMethod:@"post"];
NSData *tempData = [URL_POST2 dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:tempData];
__weak typeof(self)temp =self;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSArray *array = dict[@"news"];
for (NSDictionary *dic in array) {
NewsModel *model =[NewsModel new];
[model setValuesForKeysWithDictionary:dic];
[temp.dataArray addObject:model];
}
for (NewsModel *model in temp.dataArray) {
NSLog(@"%@",model);
}
}];
}
除以上之外蝴罪,還有Get的Delegate方式請求和Post的Delegate方式請求董济,這兩種方式都需要遵守 NSURLConnectionDataDelegate協(xié)議,并實現(xiàn)協(xié)議里面的幾個方法才能進行數(shù)據(jù)操作的實現(xiàn) 要门,以下兩種方式的實現(xiàn)都是在此基礎上進行的
5虏肾、Get異步Delegate
- (IBAction)getYiDelegate:(UIButton *)sender {
NSLog(@"Get異步請求代理");
//創(chuàng)建url對象
NSURL *url =[NSURL URLWithString:BASE_URL];
//創(chuàng)建請求對象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//創(chuàng)建連接對象并實現(xiàn)代理
NSURLConnection *connection =[NSURLConnection connectionWithRequest:request delegate:self];
//開始執(zhí)行
[connection start];
}
6、Post異步Delegate
- (IBAction)postYiDelegate:(id)sender {
NSLog(@"Post異步請求代理");
NSURL *url =[NSURL URLWithString:URL_POST1];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"post"];
NSData *tempData =[URL_POST2 dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:tempData];
NSURLConnection *connection =[NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}
NSURLConnectionDataDelegate方法的實現(xiàn)
//接收到服務器響應的時候出發(fā)的方法
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//準備數(shù)據(jù)接收 先進行數(shù)據(jù)初始化
self.tempData =[NSMutableData data];
}
//接收請求的數(shù)據(jù)
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//將每次接收到的數(shù)據(jù)拼接到原有數(shù)據(jù)包的后面
[_tempData appendData:data];
}
//數(shù)據(jù)加載完畢 開始解析
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSError *error;
NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:_tempData options:NSJSONReadingAllowFragments error:&error];
NSArray *array =dict[@"news"];
for (NSDictionary *dic in array) {
NewsModel *model =[NewsModel new];
[model setValuesForKeysWithDictionary:dic];
[self.dataArray addObject:model];
}
for (NewsModel *model in _dataArray) {
NSLog(@"%@",model);
}
}
//打印失敗信息
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"文件連接出現(xiàn)了error = %@",error);
}
7欢搜、Get Session異步請求
- (IBAction)getSession:(UIButton *)sender {
//準備url對象
NSURL *url =[NSURL URLWithString:BASE_URL]封豪;
//創(chuàng)建session對象
NSURLSession *session =[NSURLSession sharedSession];
__weak typeof(self)temp =self;
//創(chuàng)建task(該方法內部默認使用get)直接進行傳遞url即可
NSURLSessionDataTask *dataTask =[session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
temp.dataArray = [NSMutableArray arrayWithCapacity:1];
//數(shù)據(jù)操作
NSDictionary *dic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSArray *array =dic[@"news"];
for (NSDictionary *dict in array) {
NewsModel *model = [NewsModel new];
[model setValuesForKeysWithDictionary:dict];
[temp.dataArray addObject:model];
}
}];
//數(shù)據(jù)操作
[dataTask resume];
for (NewsModel *model in _dataArray) {
NSLog(@"%@",model);
}
}
8、Post Session異步請求
- (IBAction)postSession:(UIButton *)sender {
NSLog(@"postSession-異步請求");
//創(chuàng)建URL對象
NSURL *url =[NSURL URLWithString:URL_POST1];
//創(chuàng)建請求對象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"post"];
NSData *tempdata = [URL_POST2 dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:tempdata];
// 3 建立會話 session支持三種類型的任務
// NSURLSessionDataTask //加載數(shù)據(jù)
// NSURLSessionDownloadTask //下載
// NSURLSessionUploadTask //上傳
NSURLSession *session =[NSURLSession sharedSession];
// NSLog(@"%d",[[NSThread currentThread] isMainThread]);
__weak typeof(self)temp = self;
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//解析
_dataArray = [NSMutableArray arrayWithCapacity:1];
NSDictionary *dic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSArray *array =dic[@"news"];
for (NSDictionary *dict in array) {
NewsModel *model = [NewsModel new];
[model setValuesForKeysWithDictionary:dict];
[_dataArray addObject:model];
}
// NSLog(@"%@",dic);
// NSLog(@"%d----",[[NSThread currentThread] isMainThread]);
//回到主線程 刷新數(shù)據(jù) 要是刷新就在這里面
dispatch_async(dispatch_get_main_queue(), ^{
// [temp.tableView reloadData];
for (NewsModel *model in _dataArray) {
NSLog(@"%@",model);
}
});
}];
//啟動任務
[dataTask resume];
}
好了炒瘟,以上就是這篇文章的所有內容吹埠,筆者在此表示感謝~~~~~