網(wǎng)絡(luò)數(shù)據(jù)請(qǐng)求自身心得

今天來(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 =""

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末苍碟,一起剝皮案震驚了整個(gè)濱河市酒觅,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌微峰,老刑警劉巖阐滩,帶你破解...
    沈念sama閱讀 221,406評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異县忌,居然都是意外死亡掂榔,警方通過(guò)查閱死者的電腦和手機(jī)继效,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,395評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)装获,“玉大人瑞信,你說(shuō)我怎么就攤上這事⊙ㄔィ” “怎么了凡简?”我有些...
    開(kāi)封第一講書(shū)人閱讀 167,815評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)精肃。 經(jīng)常有香客問(wèn)我秤涩,道長(zhǎng),這世上最難降的妖魔是什么司抱? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,537評(píng)論 1 296
  • 正文 為了忘掉前任筐眷,我火速辦了婚禮,結(jié)果婚禮上习柠,老公的妹妹穿的比我還像新娘匀谣。我一直安慰自己,他們只是感情好资溃,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,536評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布武翎。 她就那樣靜靜地躺著,像睡著了一般溶锭。 火紅的嫁衣襯著肌膚如雪宝恶。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 52,184評(píng)論 1 308
  • 那天趴捅,我揣著相機(jī)與錄音垫毙,去河邊找鬼。 笑死驻售,一個(gè)胖子當(dāng)著我的面吹牛露久,可吹牛的內(nèi)容都是我干的更米。 我是一名探鬼主播欺栗,決...
    沈念sama閱讀 40,776評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼征峦!你這毒婦竟也來(lái)了迟几?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,668評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤栏笆,失蹤者是張志新(化名)和其女友劉穎类腮,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體蛉加,經(jīng)...
    沈念sama閱讀 46,212評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蚜枢,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,299評(píng)論 3 340
  • 正文 我和宋清朗相戀三年缸逃,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片厂抽。...
    茶點(diǎn)故事閱讀 40,438評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡需频,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出筷凤,到底是詐尸還是另有隱情昭殉,我是刑警寧澤,帶...
    沈念sama閱讀 36,128評(píng)論 5 349
  • 正文 年R本政府宣布藐守,位于F島的核電站挪丢,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏卢厂。R本人自食惡果不足惜乾蓬,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,807評(píng)論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望足淆。 院中可真熱鬧巢块,春花似錦、人聲如沸巧号。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,279評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)丹鸿。三九已至越走,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間靠欢,已是汗流浹背廊敌。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,395評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留门怪,地道東北人骡澈。 一個(gè)月前我還...
    沈念sama閱讀 48,827評(píng)論 3 376
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像掷空,于是被迫代替她去往敵國(guó)和親肋殴。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,446評(píng)論 2 359