IOS 網路淺析-(九 NSURLSession代理簡介),iosnsurlsession

來源:互聯網
上載者:User

IOS 網路淺析-(九 NSURLSession代理簡介),iosnsurlsession

從最開始什麼都不懂的小白,到到現在略知一二的小孩。我覺得不僅僅是我,大家應該都會注意到代理幾乎貫穿著IOS,那麼問題來了,我接下來要說什麼呢,那就是。標題的內容啦。上篇網路系列的文章我介紹了NSURLSession,趁熱打鐵,這篇就介紹一下NSURLSession代理的實現。

NSURLSession這塊其實並不難,但是有人會說有點亂,大家不要擔心,不容易實現的api總會有大牛實現三方的,稍後我會為大家獻上“微不足道”的三方。

*關於NSURLSession我想再寫一篇到兩篇,雖然實際開發中有可能用不到,但是原生的我們還是知道比較好,過於依賴三方,大神也會成為小白*

言歸正轉,代碼中現本事:

////  ViewController.m//  CX-NSURLSession代理簡介////  Created by ma c on 16/3/21.//  Copyright © 2016年 xubaoaichiyu. All rights reserved.//#import "ViewController.h"@interface ViewController ()<NSURLSessionDataDelegate>@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    }//這是為了測試而建立的點擊螢幕事件。-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{        //代理 測試        NSURL * url = [NSURL URLWithString:@"http://localhost/login.php?username=haha&password=123"];    //建立自訂Session        NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];        NSURLSessionTask * task = [session dataTaskWithURL:url];    //開啟任務    [task resume];    }#pragma mark - deleDate//接受到伺服器響應-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{    //__FUNCTION__ c語言字串用s    NSLog(@"%s",__FUNCTION__);            //允許伺服器回傳資料    completionHandler(NSURLSessionResponseAllow);    }//接受伺服器回傳的資料可能執行多次-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);    }//請求成功或者失敗-(void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error{    NSLog(@"%@",error);}@end

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.