IOS网络请求类(NSURLCollection)

*NSURLCollection ios9已废弃

在Xcode 7 上需要在info.plist里添加ATS,允许所有(用souse 打开)

    <key>NSAppTransportSecurity</key>

    <dict>

        <key>NSAllowsArbitraryLoads</key>

        <true/>

    </dict>

即可

一.NSURL对象初始化注意:

     1.url里面有空格。

     2.url里面不能有汉字。

     3.如果里面有汉字需要编码

     urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

二.异步请求方式

1> + sendAsynchronousRequest

// 1.创建地址
    NSString *urlStr = @"http://d3.s.hjfile.cn/2012/201202_3/43904b09-24e1-4fdb-8b46-d3dba3323278.mp3";
    // 2.创建url
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    // 3.创建NSURLRequest
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 4.开始请求数据
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSLog(@"%@",data);
    }];

2> + connectionWithRequest delagete 需要遵守代理方法<NSURLConnectionDataDelegate,NSURLConnectionDelegate>

// 第二种
- (void)viewDidLoad {
    [super viewDidLoad];
    [NSURLConnection connectionWithRequest:request delegate:self];
    
}
#pragma mark - NSURLConnection 代理方法
// 收到请求
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // 1.获得文件名称
    NSString *fileName = [response suggestedFilename];
    // 2.文件大小
    long long fileSize = [response expectedContentLength];
    // 3.文件类型
    NSString *fileType = [response MIMEType];
    // 4.状态码(需要转化)
    // 404,403,500,200
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSInteger code  = httpResponse.statusCode;
    // 5.响应头信息
    NSDictionary *body = [httpResponse allHeaderFields];
    
}

// 接收到数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //1.追加数据
    //2.计算进度
    //3.刷新界面
    //4.写入数据
}
// 请求失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    
}
// 请求完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //1.刷新界面
    //2.数据解析和封装数据模型
}

3> 需要创建对象,手动执行,遵守代理<NSURLConnectionDataDelegate,NSURLConnectionDelegate>

// 第三种
- (void)viewDidLoad {
    [super viewDidLoad];
    // 1.先创建对象

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

    // 2.手动执行,代理方法

    [connection start];
}
原文地址:https://www.cnblogs.com/3WWanXiang/p/4904770.html