美文网首页iOS进阶高级网络
iOS开发高级进阶(11-12)-网络编程

iOS开发高级进阶(11-12)-网络编程

作者: 逸飞u | 来源:发表于2016-03-15 20:09 被阅读332次

    TCP/IP简介

    REST

    • 服务端API设计模式:
      1. 使用Path指示资源
      2. HTTP Verb表示操作
    • API方法 幂等(idempotence)幂等性 [ai'dempətəns,-tənsi]:多次执行效果一样

    iOS的网络

    iOS的网络

    BSD Scoket

    参考:
    https://en.wikipedia.org/wiki/Berkeley_sockets#BSD_and_POSIX_sockets

    BSD Scoket图示

    CFNetwork

    CFNetwork

    代码:

    CFStringRef s =CFSTR("http://www.apple.com");
    
    CFURLRef myURL=CFURLCreateWithString(kCFAllocatorDefault, s, 0);
    CFStringRef requestMethod = CFSTR("GET");
    
    CFHTTPMessageRef myRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, myURL, kCFHTTPVersion1_1);
    
    CFHTTPMessageSetBody(myRequest, bodyData);
    CFHTTPMessageSetHeaderFieldValue(myRequest, headerField, value);
    
      // CFReadStreamCreateForHTTPRequest 已过时
        CFReadStreamRef myReadStream = CFReadStreamCreateWithFile(<#CFAllocatorRef alloc#>, <#CFURLRef fileURL#>);
        CFReadStreamOpen(myReadStream);
    

    URL Loading System

    现在用NSURLSession
    NSURLConnection的最简用法对比

    //NSURLSession 读取URL
        NSURL *myURL1=[NSURL URLWithString:@"http://www.bing.com"];
        NSURLSession * session = [NSURLSession sharedSession];
        [[session dataTaskWithURL:myURL1 completionHandler:^(NSData * data,NSURLResponse *response,NSError *error){
        }
          ]resume];
    
    //NSURLConnection 读取URL
        NSURL *myURL2=[NSURL URLWithString:@"http://www.bing.com"];
        NSURLRequest *Request=[NSURLRequest requestWithURL:myURL2];
    
    //已过时
    [NSURLConnection sendAsynchronousRequest:Request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response,NSData *data,NSError *error){
    }
     ];
    

    NSURLSession

    • 结构


      NSURLSession的结构
    委托
    • 基本用法
    1. 根据Session类型选择NSURLSessionConfiguration

    2. 设置Configuration,如指定NSURLCache灯

    3. 用Configuration创建Session
      [NSURLSession sessionWithConfiguration:<#(nonnull NSURLSessionConfiguration *)#>];

        [NSURLSession sessionWithConfiguration:<#(nonnull NSURLSessionConfiguration *)#> 
                      delegate:<#(nullable id<NSURLSessionDelegate>)#> 
                      delegateQueue:<#(nullable NSOperationQueue *)#>];
      
    4. 在session 里创建网络访问任务

    5. 启动任务
      NSURLSessionTask *task = [[NSURLSessionTask alloc]init] ;
      [task resume];

    NSURLSession类型

    Session Configuration类型
    1. Default sessions:(全局的)
      • 基于文件系统的缓存
      • 在keychain里保存凭证
    2. Ephemeral sessions:(私有的)
      • 全内存缓存
      • 数据仅在Session期间存在
    3. Background sessions
      • 另有专门的进程处理数据传输

      • 其它同Default

        //代码
        @interface NSURLSessionConfiguration : NSObject <NSCopying>
        + (NSURLSessionConfiguration *)defaultSessionConfiguration;
        + (NSURLSessionConfiguration *)ephemeralSessionConfiguration;
        + (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier;
        
    Task类型
    1. Data Task(适合临时与服务端通讯)
      NSURLSession * task = [[NSURLSession alloc]init];
      [task dataTaskWithURL:<#(nonnull NSURL *)#>];
    1. Download Task(接收文件,支持后台下载)
      NSURLSession * task = [[NSURLSession alloc]init];
      [task downloadTaskWithURL:<#(nonnull NSURL *)#>];

    2. Upload Task(发送文件,支持后台上传)

       NSURLSession * task = [[NSURLSession alloc]init];
       [task uploadTaskWithRequest:<#(nonnull NSURLRequest *)#> fromData:<#(nonnull NSData *)#>];
      

    网络连接状态

    引入SystemConfiguration.framework

    @import SystemConfiguration;
    
    SCNetworkReachabilityCreateWithAddressPair ( 
        CFAllocatorRef allocator, 
        const struct sockaddr *localAddress, 
        const struct sockaddr *remoteAddress );
    
    SCNetworkReachabilityGetFlags(
        <#SCNetworkReachabilityRef  _Nonnull target#>, 
        <#SCNetworkReachabilityFlags * _Nonnull flags#>)
    
      //监听网络变化        
      SCNetworkReachabilitySetCallback(
        <#SCNetworkReachabilityRef  _Nonnull target#>, 
        <#SCNetworkReachabilityCallBack  _Nullable callout#>, 
        <#SCNetworkReachabilityContext * _Nullable context#>)
    

    杨武老师说不是特别好用,建议听下一课内容


    AFNetworking

    第三方网络访问库
    https://github.com/AFNetworking/AFNetworking

    特色:

    • Serialization Modules 从原始数据格式转换成特定数据格式
    • 对UIKit做了扩展

    安装:

    方法1. 使用CocoaPods:Podfile

    source 'https://github.com/cocoaPods/Specs.git'
    platform:ios,'8.0'
    pod 'AFNetworking', '~>3.0'
    

    方法2. Carthage:Cartfile

    //1.
      github "AFNetworking/AFNetworking" ~>3.0
    
    //2.手工把静态库打包到项目
    

    概述:

    Overview

    代码示范:

    1. 下载
    //下载文件
      NSURLSessionConfiguration * config =[NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager =[[AFURLSessionManager alloc]initWithSessionConfiguration:config];
    
    NSURL *url =[NSURL URLWithString:@"http://example.com/download.zip"];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    
    NSURLSessionDownloadTask *downloadTask =
    [manager downloadTaskWithRequest:request progress:nil
                         destination:^NSURL *(NSURL *targetPath,NSURLResponse *response){
                             NSFileManager *fm = [NSFileManager defaultManager];
                             NSURL *docURL=[fm URLForDirectory:NSDocumentDirectory
                                                      inDomain:NSUserDomainMask
                                             appropriateForURL:nil
                                                                create:NO error:nil];
          
                             return [docURL URLByAppendingPathComponent:[response suggestedFilename]];
                         } completionHandler:^(NSURLResponse *response,NSURL *filePath,NSError *error){
                             NSLog(@"File downloaded to:%@",filePath);
                         }
     
     ];
    [downloadTask resume];
    

    2.上传

    //上传
    NSURLSessionConfiguration * config =[NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager =[[AFURLSessionManager alloc]initWithSessionConfiguration:config];
    
    NSURL *url =[NSURL URLWithString:@"http://example.com/upload"];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    
    NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
    NSURLSessionUploadTask *uploadTask=
    [manager uploadTaskWithRequest:request fromFile:filePath progress:nil
                 completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){
                     if(error){
                         NSLog(@"Error:%@,error");
                     }else{
                         NSLog(@"Seccess:%@ %@ ,response,responseObject");
                     }
                 }
     ];
    [uploadTask resume];
    
    • Serialization (有序化)

      • Request Serialization
      • Response Serialization
    • HTTPS支持

    • Reachability

      • URL
      • Domain
      • different type of connection
      • Wifi

    UIKit Extensions

    UIKit与网络结合,例如:

    [imageView setImageWithURL:imgURL];
    

    调试工具

    相关文章

      网友评论

        本文标题:iOS开发高级进阶(11-12)-网络编程

        本文链接:https://www.haomeiwen.com/subject/ddbflttx.html