IOS网络编程

IOS网络编程

NSURLConnection

NSURLSession是NSURLConnection 的替代者,在2013年苹果全球开发者大会(WWDC2013)随ios7一起发布,是对NSURLConnection进行了重构优化后的新的网络访问接口。从\color{red}{iOS9.0}开始, NSURLConnection中发送请求的两个方法已过期(同步请求,异步请求),初始化网络连接(initWithRequest: delegate:)的方法也被设置为过期,系统不再推荐使用,建议使用NSURLSession发送网络请求。先简单回顾下NSURLConnectiion

  • \color{red}{常用类}

      1. NSURL:请求地址  
      2. NSURLRequest:封装一个请求,保存发给服务器的全部数据,包括一个   NSURL对象,请求方法、请求头、请求体....  
      3. NSMutableURLRequest:NSURLRequest的子类,可以之定义请求头  
      4. NSURLConnection:负责发送请求,建立客户端和服务器的连接。发送NSURLRequest的数据给服务器,并收集来自服务器的响应数据
    
  • \color{red}{使用}

      1. 创建一个NSURL对象,设置请求路径(设置请求路径)  
      2. 传入NSURL创建一个NSURLRequest对象,设置请求头和请求体(创建请求对象)  
      3. 使用NSURLConnection发送NSURLRequest(发送请求)
    

模型图如下:


模型图
  • \color{red}{发送同步请求 }
 - (void)sendSyncRequest {
    NSString *strUrl = @"http://127.0.0.1:5000/student/userInfo";
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    NSURLResponse *response = nil;
    NSError *error;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
    NSLog(@"result===%@",result);
    
}

  • \color{red}{发送异步请求 }
- (void)sendASyncRequest {
    NSString *strUrl = @"http://127.0.0.1:5000/student/userInfo";
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
           NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
        NSLog(@"===%@",result);
    }];
}

上面的案例是利用block来发送的异步请求,当然,我们也可以使用代理的方式来发送异步请求,这里涉及\color{green}{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 

代理继承关系图如下:


NSURLConnection代理.png
  • <font color='red'>NSMutableURLRequest常用方法 </font>
    //设置请求超时等待时间(超过这个时间就算超时,请求失败
    - (void)setTimeoutInterval:(NSTimeInterval)seconds;
    //设置请求方法(比如GET和POST)
    - (void)setHTTPMethod:(NSString *)method
    //设置请求体
    - (void)setHTTPBody:(NSData *)data;
    //设置请求头
    - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;

NSURLSession

高度异步,线程安全

其类图结构如下:


NSURLSession类图结构.png
  • \color{red}{基本使用}
- (void)jsonTest {
    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSString * url = [NSString stringWithFormat:@"http://api.androidhive.info/volley/person_object.json"];
    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSURLSessionDataTask * task = [session dataTaskWithRequest:request];
    [task resume];  //启动任务
    }

说明

  1. 我们首先创建NSURLSessionConfiguration对象,这个对于下载或者上传来说是至关重要的第一步,(You use this object to configure the timeout values, caching policies, connection requirements, and other types of information that you intend to use with your NSURLSession object.)否则,我们可以利用sharedSession来创建NSURLSession,但这样的话你就没有办法设置delegate了。
  2. 创建一个session对象,指定配置对象,代理以及执行队列
  3. 利用session来创建任务对象Task,正如以上类图结构所示的几种Task对象,值得一提的是,当我们利用session创建对象以后,这个task默认是处于suspended(挂起)状态,如果我们要执行这个任务,那么利用resume方法来激活它。

当我们激活一个任务以后,那么相关的代理将被回调,以下为官方介绍:
After you start a task, the session calls methods on its delegate, as follows:

  1. If the initial handshake with the server requires a connection-level challenge (such as an SSL client certificate), NSURLSession calls either the URLSession:task:didReceiveChallenge:completionHandler: or URLSession:didReceiveChallenge:completionHandler: delegate method.

  2. If the task’s data is provided from a stream, the NSURLSession object calls the delegate’s URLSession:task:needNewBodyStream: delegate method to obtain an instance of NSInputStream that provides the body data for the new request.

  3. During the initial upload of body content to the server (if applicable), the delegate periodically receives URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend: callbacks that report the progress of the upload.

  4. The server sends a response.

  5. If the response indicates that authentication is required, the session calls its delegate’s URLSession:task:didReceiveChallenge:completionHandler: method. Go back to step 2.

  6. If the response is an HTTP redirect response, the NSURLSession object calls the delegate’s URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler: method. That delegate method calls the provided completion handler with either the provided NSURLRequest object (to follow the redirect), a new NSURLRequest object (to redirect to a different URL), or nil (to treat the redirect’s response body as a valid response and return it as the result).

     If you decide to follow the redirect, go back to step 2.
    
     If the delegate doesn’t implement this method, the redirect is followed up to the maximum number of redirects.
    
  7. For a download (or redownload) task created by calling downloadTaskWithResumeData: or downloadTaskWithResumeData:completionHandler:, NSURLSession calls the delegate’s URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes: method with the new task object.

  8. For a data task, the NSURLSession object calls the delegate’s URLSession:dataTask:didReceiveResponse:completionHandler: method. Decide whether to convert the data task into a download task, and then call the completion handler to convert, continue, or cancel the task. If your app chooses to convert the data task to a download task, NSURLSession calls the delegate’s URLSession:dataTask:didBecomeDownloadTask: method with the new download task as a parameter. After this call, the delegate receives no further callbacks from the data task, and begins receiving callbacks from the download task.

  9. During the transfer from the server, the delegate periodically receives a task-level callback to report the progress of the transfer. For a data task, the session calls the delegate’s URLSession:dataTask:didReceiveData:method with the actual pieces of data as they’re received. For a download task, the session calls the delegate’s URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite: method with the number of bytes successfully written to disk. If the user tells your app to pause the download, cancel the task by calling the cancelByProducingResumeData: method. Later, if the user asks your app to resume the download, pass the returned resume data to either the downloadTaskWithResumeData: or downloadTaskWithResumeData:completionHandler: method to create a new download task that continues the download. (Go to step 1.)

  10. For a data task, the NSURLSession object may call the delegate’s URLSession:dataTask:willCacheResponse:completionHandler: method. Your app should then decide whether to allow caching. If you don’t implement this method, the default behavior is to use the caching policy specified in the session’s configuration object.

  11. If the response is multipart encoded, the session may call the delegate’s didReceiveResponse method again, followed by zero or more additional didReceiveData calls. If this happens, go to step 8 (handling the didReceiveResponse call).

  12. If a download task completes successfully, then the NSURLSession object calls the task’s URLSession:downloadTask:didFinishDownloadingToURL: method with the location of a temporary file. Your app must either read the response data from this file or move it to a permanent location before this delegate method returns.

  13. When any task completes, the NSURLSession object calls the delegate’s URLSession:task:didCompleteWithError: method with either an error object or nil (if the task completed successfully). If the download task can be resumed, the NSError object’s userInfo dictionary contains a value for the NSURLSessionDownloadTaskResumeData key. Your app should pass this value to call downloadTaskWithResumeData: or downloadTaskWithResumeData:completionHandler: to create a new download task that continues the existing download. If the task can’t be resumed, your app should create a new download task and restart the transaction from the beginning. In either case, if the transfer failed for any reason other than a server error, go to step 3 (creating and resuming task objects).

  14. If you no longer need a session, you can invalidate it by calling either invalidateAndCancel (to cancel outstanding tasks) or finishTasksAndInvalidate (to allow outstanding tasks to finish before invalidating the object). If you don’t invalidate the session, it automatically goes away when your app is terminated (unless it’s a background session with active tasks). After invalidating the session, when all outstanding tasks have been canceled or have finished, the session calls the delegate’s URLSession:didBecomeInvalidWithError: method. When that delegate method returns, the session disposes of its strong reference to the delegate.

  15. If your app cancels an in-progress download, the NSURLSession object calls the delegate’s URLSession:task:didCompleteWithError: method as though an error occurred.

demo地址:https://github.com/UCliwenbin/IOSNetWorkPrj

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,014评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,796评论 3 386
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,484评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,830评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,946评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,114评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,182评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,927评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,369评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,678评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,832评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,533评论 4 335
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,166评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,885评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,128评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,659评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,738评论 2 351

推荐阅读更多精彩内容

  • NSURLSession 使用步骤使用NSURLSession对象创建Task,然后执行Task -(void)g...
    BEYOND黄阅读 901评论 0 0
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,312评论 0 10
  • 使用NSURLConnection实现下载 1. 小文件下载 第一种方式(NSData) 第二种方式(NSURLC...
    搁浅的青蛙阅读 1,946评论 3 10
  • (稻盛哲学学习会)打卡第52天 姓名:王建凤 部门:杭州安简 组别:努力三组 【知~学习】 诵读《活法》第四章 :...
    又昂阅读 134评论 0 0
  • 2017年惊蛰,我带一家老小去游春。我们驱车一个小时来到绶溪公园,这里早就人头攒动,欢声笑语。我牵着儿子的手...
    醉烟渔人阅读 499评论 2 3