IOS网络编程

IOS网络编程

NSURLConnection

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

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

模型图如下:


IOS网络编程_第1张图片
模型图
 - (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);
    
}

- (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来发送的异步请求,当然,我们也可以使用代理的方式来发送异步请求,这里涉及 个代理,如下:

 //当接收到服务器的响应(连通了服务器)时会调用
 -(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 

代理继承关系图如下:


IOS网络编程_第2张图片
NSURLConnection代理.png
  • NSMutableURLRequest常用方法
    //设置请求超时等待时间(超过这个时间就算超时,请求失败
    - (void)setTimeoutInterval:(NSTimeInterval)seconds;
    //设置请求方法(比如GET和POST)
    - (void)setHTTPMethod:(NSString *)method
    //设置请求体
    - (void)setHTTPBody:(NSData *)data;
    //设置请求头
    - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;

NSURLSession

高度异步,线程安全

其类图结构如下:


NSURLSession类图结构.png
- (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/NSURLSessionDemo.git

你可能感兴趣的:(IOS网络编程)