今天来说说关于iOS开发过程中的网络数据请求。
现在常用的网络数据请求常见的有四种方式:同步GET,同步POST,异步GET,异步POST。
一,同步GET
//1.将网址初始化成一个OC字符串对象NSString*urlString = [NSStringstringWithFormat:@"%@query=%@&ion=%@output=json&ak=6E823f587c95f0148c19993539b99295", kBusinessInfoURL,@"银行",@"济南"];//如果网址中存在中文,进行URLEncode.NSString*newUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//2.构建网络URL对象,NSURLNSURL*url = [NSURLURLWithString:newUrlStr];//3.创建网络请求NSURLRequest*request = [NSURLRequestrequestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheDatatimeoutInterval:10];//创建同步连接NSURLResponse*response =nil;NSError*error =nil;NSData*data = [NSURLConnectionsendSynchronousRequest:request reurningResponse:&response error:&error];
当创建好同步连接以后,就可以采用响应的方法进行解析。下面创建异步链接也是一样的
二,同步POST
//1.根据网址初始化OC字符串对象NSString*urlStr = [NSStringstringWithFormat:@"%@",kVideoURL];//2.创建NSURL对象NSURL*url = [NSURLURLWithString:urlStr];//3.创建请求NSMutableURLRequest*request = [NSMutableURLRequestrequestWithURL:url];//4,创建参数字符串对象NSString*parmStr =@"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10";//5.将字符串转成NSData对象NSString*parmData = [parmStr dataUsingEncoding:NSUTF8StringEncoding];//6.设置请求体[request setHTTPBody:pramData];//7.设置请求体[request setHTTPMethod:@"POST"];//创建同步连接NSData*data = [NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:nil];
三,异步GET
NSString*urlStr = [NSStringstringWithFormat:@"http://image.zcool.com.cn/56/13/1308200901454.jpg"];NSString*newStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];NSURL*url = [NSURLURLWithString:newStr];NSURLRequest*request = [NSURLRequestrequestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheDatatimeoutIntercal;10];//异步链接(形式1,较少用)[NSURLConnectionsendAsynchronousRequest:requst queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse*response,NSData*data,NSError*connectionError) {self.imageView.image = [UIImageimageWithData:data];// 解析NSDictionary*dic = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableContainerserror:nil];NSLog(@"%@", dic); }];
四,异步POST
// POST请求NSString*urlString = [NSStringstringWithFormat:@"%@",kVideoURL];//创建url对象NSURL*url = [NSURLURLWithString:urlString];//创建请求NSMutableURLRequest*request = [NSMutableURLRequestrequestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheDatatimeoutInterval:10];//创建参数字符串对象NSString*parmStr = [NSStringstringWithFormat:@"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10"];//将字符串转换为NSData对象NSData*data = [parmStr dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPBody:data]; [request setHTTPMethod:@"POST"];//创建异步连接(形式二)[NSURLConnectionconnectionWithRequest:request delegate:self];
一般的,当创建异步连接时,很少用到第一种方式,经常使用的是代理方法。关于NSURLConnectionDataDelegate,我们进场使用的协议方法为一下几个:
// 服务器接收到请求时- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response{}// 当收到服务器返回的数据时触发, 返回的可能是资源片段- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data{}// 当服务器返回所有数据时触发, 数据返回完毕- (void)connectionDidFinishLoading:(NSURLConnection*)connection{}// 请求数据失败时触发- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error{NSLog(@"%s", __FUNCTION__);}
最后,分析一下这几种呢网络请求的区别。
GET请求和POST请求的区别:
viewcontroller.swift
//表格
vartable:UITableView?
vartableDataArr:[NewsModel]?
var mjHeaderView:MJRefreshHeaderView?//下拉刷新
var mjFooterView:MJRefreshFooterView?//上拉加载
functableView(_tableView:UITableView, numberOfRowsInSection section:Int) ->Int{
ifletcount =tableDataArr?.count{
returncount
}
return0
}
functableView(_tableView:UITableView, cellForRowAt indexPath:IndexPath) ->UITableViewCell{
letidentifier ="cell"
varcell = tableView.dequeueReusableCell(withIdentifier: identifier)
ifcell ==nil{
cell =UITableViewCell.init(style: .subtitle, reuseIdentifier: identifier)
}
letoneNew =self.tableDataArr![indexPath.row]
cell?.textLabel?.numberOfLines = 0
cell?.detailTextLabel?.numberOfLines = 0
cell?.textLabel?.text= oneNew.title
cell?.detailTextLabel?.text= oneNew.content
returncell!
}
// MARK:=============请求网络数据=================
funcrequestNetWorkDataAndUpdateUI() ->Void{
UIApplication.shared.isNetworkActivityIndicatorVisible = true
//请求网络数据
leturlService =URLService()
urlService.getNewsData(channel:"头条", startNum:0) { (data, success)in
DispatchQueue.main.async{
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.mjHeaderView?.endRefreshing()
}
if!success{
DispatchQueue.main.async{
letalertVC =UIAlertController(title:nil, message: dataas!String, preferredStyle: .alert)
letconfinBtn =UIAlertAction(title:"确定", style: .default, handler:nil)
alertVC.addAction(confinBtn)
self.present(alertVC, animated:true, completion:nil)
}
return
}
self.tableDataArr= dataas? [NewsModel]
DispatchQueue.main.async{
self.table?.reloadData()
}
}
}
overridefuncviewWillAppear(_animated:Bool) {
super.viewWillAppear(animated)
self.requestNetWorkDataAndUpdateUI()
}
overridefuncviewDidLoad() {
super.viewDidLoad()
self.table=UITableView.init(frame:self.view.frame, style: .plain)
self.table?.dataSource=self
self.view.addSubview(self.table!)
self.mjHeaderView = MJRefreshHeaderView(scrollView:self.table!)
// self.mjHeaderView?.delegate = self
}
overridefuncdidReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//URLService.swift
funcgetNewsData(channel:String,startNum:Int,completion:@escaping(Any,Bool)->Void) ->Void{
//使用GET请求数据
// (1) 网址字符串拼接
var urlStr = "http://api.jisuapi.com/news/get?channel=\(channel)&start=\(startNum)&num=15&appkey=de394933e1a3e2db"
// (2) 转码
urlStr = urlStr.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlFragmentAllowed)!
// (3) 封装为URL对象
leturl =URL(string: urlStr)
// (4) 封装为URLRequest对象
letreq =URLRequest(url: url!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval:5.0)
// (5) 使用URLSession请求网络数据
lettask:URLSessionDataTask=URLSession.shared.dataTask(with: req) { (data, response, error)in
// 如果错误
iferror !=nil{
//参数闭包的调用
completion("网络服务器错误",false)
return
}
// json数据解析
letjsonData =try?JSONSerialization.jsonObject(with: data!, options:JSONSerialization.ReadingOptions.allowFragments)
ifjsonData ==nil{
completion("网络数据错误",false)
return
}
letstatus = (jsonDataas!NSDictionary).value(forKey:"status")as!String
letmsg = (jsonDataas!NSDictionary).value(forKey:"msg")as!String
ifInt(status)! !=0{
completion(msg,false)
return
}
letresult = (jsonDataas!NSDictionary).value(forKey:"result")as!NSDictionary
letlist = result.value(forKey:"list")as!NSArray
varnewsArr:[NewsModel] = []
foriteminlist{
letdic = itemas!NSDictionary
letoneNew =NewsModel()
oneNew.title= dic.value(forKey:"title")as!String
oneNew.content= dic.value(forKey:"content")as!String
oneNew.time= dic.value(forKey:"time")as!String
oneNew.url= dic.value(forKey:"url")as!String
oneNew.weburl= dic.value(forKey:"weburl")as!String
newsArr.append(oneNew)
}
completion(newsArr,true)
}
// (6)开启任务
task.resume()
}
}
//NewsModel.swift
varchannel:String=""
varcontent =""
vartitle =""
vartime =""
varsrc =""
varcategory =""
varurl =""
varweburl =""