今天來(lái)說(shuō)說(shuō)關(guān)于iOS開(kāi)發(fā)過(guò)程中的網(wǎng)絡(luò)數(shù)據(jù)請(qǐng)求碰纬。
現(xiàn)在常用的網(wǎng)絡(luò)數(shù)據(jù)請(qǐng)求常見(jiàn)的有四種方式:同步GET允粤,同步POST崭倘,異步GET,異步POST类垫。
一司光,同步GET
//1.將網(wǎng)址初始化成一個(gè)OC字符串對(duì)象NSString*urlString = [NSStringstringWithFormat:@"%@query=%@&ion=%@output=json&ak=6E823f587c95f0148c19993539b99295", kBusinessInfoURL,@"銀行",@"濟(jì)南"];//如果網(wǎng)址中存在中文悉患,進(jìn)行URLEncode.NSString*newUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//2.構(gòu)建網(wǎng)絡(luò)URL對(duì)象,NSURLNSURL*url = [NSURLURLWithString:newUrlStr];//3.創(chuàng)建網(wǎng)絡(luò)請(qǐng)求NSURLRequest*request = [NSURLRequestrequestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheDatatimeoutInterval:10];//創(chuàng)建同步連接NSURLResponse*response =nil;NSError*error =nil;NSData*data = [NSURLConnectionsendSynchronousRequest:request reurningResponse:&response error:&error];
當(dāng)創(chuàng)建好同步連接以后残家,就可以采用響應(yīng)的方法進(jìn)行解析。下面創(chuàng)建異步鏈接也是一樣的
二售躁,同步POST
//1.根據(jù)網(wǎng)址初始化OC字符串對(duì)象NSString*urlStr = [NSStringstringWithFormat:@"%@",kVideoURL];//2.創(chuàng)建NSURL對(duì)象NSURL*url = [NSURLURLWithString:urlStr];//3.創(chuàng)建請(qǐng)求NSMutableURLRequest*request = [NSMutableURLRequestrequestWithURL:url];//4,創(chuàng)建參數(shù)字符串對(duì)象NSString*parmStr =@"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10";//5.將字符串轉(zhuǎn)成NSData對(duì)象NSString*parmData = [parmStr dataUsingEncoding:NSUTF8StringEncoding];//6.設(shè)置請(qǐng)求體[request setHTTPBody:pramData];//7.設(shè)置請(qǐng)求體[request setHTTPMethod:@"POST"];//創(chuàng)建同步連接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請(qǐng)求NSString*urlString = [NSStringstringWithFormat:@"%@",kVideoURL];//創(chuàng)建url對(duì)象NSURL*url = [NSURLURLWithString:urlString];//創(chuàng)建請(qǐng)求NSMutableURLRequest*request = [NSMutableURLRequestrequestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheDatatimeoutInterval:10];//創(chuàng)建參數(shù)字符串對(duì)象NSString*parmStr = [NSStringstringWithFormat:@"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10"];//將字符串轉(zhuǎn)換為NSData對(duì)象NSData*data = [parmStr dataUsingEncoding:NSUTF8StringEncoding];? ? [request setHTTPBody:data];? ? [request setHTTPMethod:@"POST"];//創(chuàng)建異步連接(形式二)[NSURLConnectionconnectionWithRequest:request delegate:self];
一般的陪捷,當(dāng)創(chuàng)建異步連接時(shí)回窘,很少用到第一種方式,經(jīng)常使用的是代理方法市袖。關(guān)于NSURLConnectionDataDelegate,我們進(jìn)場(chǎng)使用的協(xié)議方法為一下幾個(gè):
// 服務(wù)器接收到請(qǐng)求時(shí)- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response{}// 當(dāng)收到服務(wù)器返回的數(shù)據(jù)時(shí)觸發(fā), 返回的可能是資源片段- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data{}// 當(dāng)服務(wù)器返回所有數(shù)據(jù)時(shí)觸發(fā), 數(shù)據(jù)返回完畢- (void)connectionDidFinishLoading:(NSURLConnection*)connection{}// 請(qǐng)求數(shù)據(jù)失敗時(shí)觸發(fā)- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error{NSLog(@"%s", __FUNCTION__);}
最后啡直,分析一下這幾種呢網(wǎng)絡(luò)請(qǐng)求的區(qū)別。
GET請(qǐng)求和POST請(qǐng)求的區(qū)別:
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:=============請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)=================
? ? funcrequestNetWorkDataAndUpdateUI() ->Void{
? ? ? ? UIApplication.shared.isNetworkActivityIndicatorVisible = true
? ? ? ? //請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)
? ? ? ? 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請(qǐng)求數(shù)據(jù)
? ? ? ? // (1) 網(wǎng)址字符串拼接
? ? ? ? var urlStr = "http://api.jisuapi.com/news/get?channel=\(channel)&start=\(startNum)&num=15&appkey=de394933e1a3e2db"
? ? ? ? // (2) 轉(zhuǎn)碼
? ? ? ? urlStr = urlStr.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlFragmentAllowed)!
? ? ? ? // (3) 封裝為URL對(duì)象
? ? ? ? leturl =URL(string: urlStr)
? ? ? ? // (4) 封裝為URLRequest對(duì)象
? ? ? ? letreq =URLRequest(url: url!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval:5.0)
? ? ? ? // (5) 使用URLSession請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)
? ? ? ? lettask:URLSessionDataTask=URLSession.shared.dataTask(with: req) { (data, response, error)in
? ? ? ? ? ? // 如果錯(cuò)誤
? ? ? ? ? ? iferror !=nil{
? ? ? ? ? ? ? ? //參數(shù)閉包的調(diào)用
? ? ? ? ? ? ? ? completion("網(wǎng)絡(luò)服務(wù)器錯(cuò)誤",false)
? ? ? ? ? ? ? ? return
? ? ? ? ? ? }
? ? ? ? ? ? // json數(shù)據(jù)解析
? ? ? ? ? ? letjsonData =try?JSONSerialization.jsonObject(with: data!, options:JSONSerialization.ReadingOptions.allowFragments)
? ? ? ? ? ? ifjsonData ==nil{
? ? ? ? ? ? ? ? completion("網(wǎng)絡(luò)數(shù)據(jù)錯(cuò)誤",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)開(kāi)啟任務(wù)
? ? ? ? task.resume()
? ? }
}
//NewsModel.swift
varchannel:String=""
? ? varcontent =""
? ? vartitle =""
? ? vartime =""
? ? varsrc =""
? ? varcategory =""
? ? varurl =""
? ? varweburl =""