iOS網(wǎng)絡(luò)
-
GET:在請求URL后面以猖凛?的形式跟上發(fā)送給服務(wù)器的參數(shù),多個參數(shù)之間用&隔開
-
http://www.xc.com/login?userName=xc&password=xc123&type=Json
-
瀏覽器和服務(wù)器對URL長度有限制,因此在URL后面附帶的參數(shù)是有限的,通常不能超過1KB
-
-
POS:發(fā)送給服務(wù)器的參數(shù)全部放在請求體重唱歧,理論上post傳遞的數(shù)據(jù)量沒有限制。
-
如果只是單純的獲取數(shù)據(jù)粒竖,數(shù)據(jù)查詢颅崩,建議使用GET,其他用POST
-
1.0 JSON解析
-
1.1 JSON簡單介紹
001 問:什么是JSON
答:
(1)JSON是一種輕量級的數(shù)據(jù)格式蕊苗,一般用于數(shù)據(jù)交互
(2)服務(wù)器返回給客戶端的數(shù)據(jù)沿后,一般都是JSON格式或者XML格式(文件下載除外)
002 相關(guān)說明
(1)JSON的格式很像OC中的字典和數(shù)組
(2)標準JSON格式key必須是雙引號
003 JSON解析方案
a.第三方框架 JSONKit\SBJSON\TouchJSON
b.蘋果原生(NSJSONSerialization) 1.2 JSON解析相關(guān)代碼
(1)json數(shù)據(jù)->OC對象
//把json數(shù)據(jù)轉(zhuǎn)換為OC對象
-(void)jsonToOC
{
//1. 確定url路徑
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=33&pwd=33&type=JSON"];
//2.創(chuàng)建一個請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.使用NSURLSession發(fā)送一個異步請求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//4.當接收到服務(wù)器響應(yīng)的數(shù)據(jù)后,解析數(shù)據(jù)(JSON--->OC)
/*
第一個參數(shù):要解析的JSON數(shù)據(jù)朽砰,是NSData類型也就是二進制數(shù)據(jù)
第二個參數(shù): 解析JSON的可選配置參數(shù)
NSJSONReadingMutableContainers 解析出來的字典和數(shù)組是可變的
NSJSONReadingMutableLeaves 解析出來的對象中的字符串是可變的 iOS7以后有問題
NSJSONReadingAllowFragments 被解析的JSON數(shù)據(jù)如果既不是字典也不是數(shù)組, 那么就必須使用這個
*/
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"%@",dict);
}];
}
(2)OC對象->JSON對象
//1.要轉(zhuǎn)換成JSON數(shù)據(jù)的OC對象*這里是一個字典
NSDictionary *dictM = @{
@"name":@"wendingding",
@"age":@100,
@"height":@1.72
};
//2.OC->JSON
/*
注意:可以通過+ (BOOL)isValidJSONObject:(id)obj;方法判斷當前OC對象能否轉(zhuǎn)換為JSON數(shù)據(jù)
具體限制:
1.obj 是NSArray 或 NSDictionay 以及他們派生出來的子類
2.obj 包含的所有對象是NSString,NSNumber,NSArray,NSDictionary 或NSNull
3.字典中所有的key必須是NSString類型的
4.NSNumber的對象不能是NaN或無窮大
*/
/*
第一個參數(shù):要轉(zhuǎn)換成JSON數(shù)據(jù)的OC對象尖滚,這里為一個字典
第二個參數(shù):NSJSONWritingPrettyPrinted對轉(zhuǎn)換之后的JSON對象進行排版喉刘,無意義
*/
NSData *data = [NSJSONSerialization dataWithJSONObject:dictM options:NSJSONWritingPrettyPrinted error:nil];
//3.打印查看Data是否有值
/*
第一個參數(shù):要轉(zhuǎn)換為STring的二進制數(shù)據(jù)
第二個參數(shù):編碼方式,通常采用NSUTF8StringEncoding
*/
NSString *strM = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",strM);
(3)OC對象和JSON數(shù)據(jù)格式之間的一一對應(yīng)關(guān)系
//OC對象和JSON數(shù)據(jù)之間的一一對應(yīng)關(guān)系
-(void)oCWithJSON
{
//JSON的各種數(shù)據(jù)格式
//NSString *test = @"\"wendingding\"";
//NSString *test = @"true";
NSString *test = @"{\"name\":\"wendingding\"}";
//把JSON數(shù)據(jù)->OC對象,以便查看他們之間的一一對應(yīng)關(guān)系
//注意點:如何被解析的JSON數(shù)據(jù)如果既不是字典也不是數(shù)組(比如是NSString), 那么就必須使用這NSJSONReadingAllowFragments
id obj = [NSJSONSerialization JSONObjectWithData:[test dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@", [obj class]);
/* JSON數(shù)據(jù)格式和OC對象的一一對應(yīng)關(guān)系
{} -> 字典
[] -> 數(shù)組
"" -> 字符串
10/10.1 -> NSNumber
true/false -> NSNumber
null -> NSNull
*/
}
}
- 1.3 字典轉(zhuǎn)模型框架
(1)相關(guān)框架
a.Mantle 需要繼承自MTModel
b.JSONModel 需要繼承自JSONModel
c.MJExtension 不需要繼承漆弄,無代碼侵入性
(2)自己設(shè)計和選擇框架時需要注意的問題
a.侵入性
b.易用性睦裳,是否容易上手
c.擴展性,很容易給這個框架增加新的功能
(3)MJExtension框架的簡單使用
//1.把字典數(shù)組轉(zhuǎn)換為模型數(shù)組
//使用MJExtension框架進行字典轉(zhuǎn)模型
self.videos = [XMGVideo objectArrayWithKeyValuesArray:videoArray];
//2.重命名模型屬性的名稱
//第一種重命名屬性名稱的方法撼唾,有一定的代碼侵入性
//設(shè)置字典中的id被模型中的ID替換
+(NSDictionary *)replacedKeyFromPropertyName
{
return @{
@"ID":@"id"
};
}
//第二種重命名屬性名稱的方法廉邑,代碼侵入性為零
[XMGVideo setupReplacedKeyFromPropertyName:^NSDictionary *{
return @{
@"ID":@"id"
};
}];
JSONdemo
#import "ViewController.h"
#import "MJExtension.h"
#import "UIImageView+WebCache.h"
#import "VideosItem.h"
#import <MediaPlayer/MediaPlayer.h>
#define baseUrl @"http://120.25.226.186:32812"
@interface ViewController ()
@property(nonatomic,strong)NSMutableArray * videos ;
@end
@implementation ViewController
-(NSMutableArray *)videos
{
if (_videos==nil) {
_videos = [NSMutableArray new];
}
return _videos;
}
- (void)viewDidLoad {
[super viewDidLoad];
/**
* 模型id替換為ID
*/
[VideosItem mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
return @{@"ID":@"id"};
}];
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/video?type=JSON"];
NSURLRequest *request =[NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
/**
* 通過字典數(shù)組來創(chuàng)建一個模型數(shù)組
*/
self.videos = [VideosItem mj_objectArrayWithKeyValuesArray:dict[@"videos"]];
[self.tableView reloadData];
}];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.videos.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = @"videos";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
VideosItem *item = self.videos[indexPath.row];
cell.textLabel.text = item.name;
cell.detailTextLabel.text = item.length;
NSString *imageUrl = [baseUrl stringByAppendingPathComponent:item.image];
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"Snip20160225_341"]];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
VideosItem *item = self.videos[indexPath.row];
NSString *url = [baseUrl stringByAppendingPathComponent:item.url];
MPMoviePlayerViewController * vc = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:url]];
[self presentViewController:vc animated:YES completion:nil];
}
@end