NSURLConnection / NSURLSession/ SDWebImage

1. NSURLConnection (iOS9开始被弃用)===========================================

   此类的对象加载一个URL请求对象,通过异步/同步的方式发送请求,并获得响应。

   此类位于Foundation框架下,继承自NSObject

------------------------------

   异步/同步?

   通讯方式

   异步:在请求发送后,无需等待响应结果,而是可以继续后续其他操作,该请求的响应在回调方法中处理(通常用到的代理方法或block)。

   同步: 相对于异步,请求发送后,需在得到响应结果后,再进行后续其他操作。

   iOS的开发中,大部分的请求是通过异步方式发送。

------------------------------

2. 使用NSURLConnection(异步)

   -异步方式一:(使用代理)

      > 指定 Controller 要实现的该类的协议名称     <NSURLConnectionDataDelegate>

      > 创建NSURL对象

         [NSURL URLWithString:]; // 注意:若url中有中文,需进行转码处理,否则服务器端可能无法识别url中的参数 [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]

      > 创建NSURLRequest对象

         [NSURLRequest requestWithURL:]

      > 使用NSURLConnection加载并异步发送urlRequest,默认GET方式

         方式一:[NSURLConnection connectionWithRequest: delegate: ]

         方式二:[[NSURLConnection alloc] initWithRequest: delegate: ]

      > 实现协议方法

// 客户端收到了服务端的响应,只是收到了一个招呼,此时请求的数据还没发到客户端

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

          // 开始接收数据,注意此时接收的数据不一定是完整的。服务端发送数据时可能会分包发送,特别在一次请求的数据量很大时。所以事先需要先定义个可变变量,当数据接收到时,不断累加数据到此变量中。

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

// 数据完全接收完毕,此时可在此处理解析数据,并展示到界面上。

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

-异步方式二:(使用block)

    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse*  response, NSData*  data, NSError*  connectionError) {

        // 在此处理接收的数据:response-> 服务端的响应;data-> 被请求的数据;connectionError-> 连接过程中发生的错误

    }];

3. 数据解析json 或xml

   若返回结果为json 或xml格式的数据时,需要对数据解析后显示。

   解析json数据:

   使用NSJSONSerialization 类。

   // 将响应获得的NSData数据转换为对象

   [NSJSONSerialization JSONObjectWithData: options: error:]; 

    /*  options: 可选选项值:NSJSONReadingAllowFragments -> 允许json字符串最外层既不是NSArray 也不是NSDictionary 但必须是有效的json fragment, 例如此选项下可解析 @“ABC” 这种字符串;

     NSJSONReadingMutableLeaves-> 返回json对象中字符串类型为NSMutableString;

     NSJSONReadingMutableContainers -> 返回可变容器,如NSMutableDictionary, NSMutableArray

    可根据son串的数据形式转换成对应类型的对象,如NSArray, NSDictionary, NSString 等。*/

    // 将json对象 转换为NSData (若需向服务器发送json格式数据时需要)

    + (nullable NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;

4. 使用NSURLConnection(同步)

    无需代理或block,但考虑到用户体验,同步的方式使用的较少。

> 创建NSURL对象

         [NSURL URLWithString:];

> 发送同步请求

       方式一:[NSData dataWithContentsOfURL:]

       方式二:[NSString stringWithContentsOfURL: encoding: error: ]  // 前提是得到的响应数据可用字符串表示; NSData与NSString 的转换

       

       方式三:

> 创建NSURLRequest对象

                    [NSURLRequest requestWithURL:]

> [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]

1. NSURLSession =======================================================

   NSURLConnection的继任者,自iOS7出现。

2. NSURLSession 使用

    > 创建NSURL对象

         [NSURL URLWithString:];

    > 创建NSURLRequest对象

         [NSURLRequest requestWithURL:]

    > 创建共享会话(会话的创建方式有多种)

         [NSURLSession sharedSession]

    > 在会话下创建数据任务(任务分三种:数据,上传,下载,后续学习其他)

        NSURLSessionDataTask 会话的数据任务,在一个会话中可创建多个任务,任务类型,可相同,也可不同。

        *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *err) {

        // 处理接收的数据

    }];

> 启动任务(对任务的操作还有暂停,取消,相比NSURLConnection更加灵活)

  [task resume]

1. SDWebImage======================================================

   第三方开源库,用于处理网络图片的加载。

   官方地址:https://github.com/rs/SDWebImage

2. 使用方式:

    三种:

    a. 使用Cocoapods (第三方库管理)

    b. 拷贝所有文件到你的工程中

    c. 将SDWebImage作为静态库引入到工程中。

    

    介绍第三种方式c:

    > 下载并解压SDWebImage工程

    > 在你的工程目录下右键“Add Files to…”

    > 选择SDWebImage.xcodeproj

    > 确认“Copy items into destination group’s folder(if needed)” 是选中的。

    > 在你的工程设置中,找到“Build Phases”->”Link Binary With Libraries”

    > 点击”+”,选择 “ImageIO.framework”

    > 再点击“+”,选择“libSDWebImage.a”

    > “Build Settings”-> “Linking”->”Other Linker Flags” 设置为“-ObjC” 

    // 可以正式使用了

    > 在你的工程里需要处理网络图片的类文件中

       #import <SDWebImage/UIImageView+WebCache.h>

       [imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]

                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]

                             completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

                                ... completion code here ...

                             }];       

      或者:

      [imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]

                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

原文地址:https://www.cnblogs.com/GJ-ios/p/5701908.html