• 网络请求connection session


    网络请求:

    NSURLConnection

    发送同步请求:

    nsurlconnection发送同步请求是阻塞式,会阻塞当前线程

    发送异步请求:

    nsurlconnection发送异步请求底层是开启子线程发送请求,回调默认是在主线程中回调,如果需要在子线程中回调可以设置代理队列setDelegateQueue:子线程队列.

    PS:请求大的响应数据时使用delegate方式更加适合

    NSURLConnection与NSRunLoop

    #import "ViewController.h"
    
    @interface ViewController () <NSURLConnectionDataDelegate>
    /** runLoop */
    @property (nonatomic, assign) CFRunLoopRef runLoop;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        // 如果在子线程中使用NSURLConnection发送请求是不会有效果,因为子线程的runloop没有启动,子线程runloop默认是不启动的
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSURLConnection *conn = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com/images/234234324limgAB/2342lkjasdf3kkkkk.jpg"]] delegate:self];
            // 决定代理方法在哪个队列中执行
            [conn setDelegateQueue:[[NSOperationQueue alloc] init]];
            
            // 启动子线程的runLoop
    //        [[NSRunLoop currentRunLoop] run];
            
            // 保存当前runloop
            self.runLoop = CFRunLoopGetCurrent();
            
            // 启动runLoop
            CFRunLoopRun();
        });
    }
    
    #pragma mark - <NSURLConnectionDataDelegate>
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        NSLog(@"didReceiveResponse******%@", [NSThread currentThread]);
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        
        NSLog(@"didReceiveData******%@", [NSThread currentThread]);
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        NSLog(@"connectionDidFinishLoading******%@", [NSThread currentThread]);
        
        // 停止RunLoop
        CFRunLoopStop(self.runLoop);
    }
    
    @end
    

    NSURLSession

    使用NSURLSession 对象创建Task,然后执行Task

    Task的类型: NSURLSessionTask抽象类, 派生出子类有NSURLSessionDataTask,NSURLSesssionDownloadTask,NSURLSessionDataTask又派生出NSURLSessionUploadTask

    NSURLSessionTask(抽象类)

    • NSURLSessionDataTask
      • NSURLSessionUploadTask
    • NSURLSessionDownloadTask

    文件上传:

    文件解压缩:

     ZipArchive框架

    小文件写入:

    NSData

    大文件写入

    NSFileHandle

    NSOutPutStream

  • 相关阅读:
    Spring中使用Log4j记录日志
    Spring MVC异常处理实例
    Spring MVC静态资源实例
    Spring MVC页面重定向实例
    Spring MVC表单实例
    Eclipse4.6安装Tomcat插件时报错:Unable to read repository at http://tomcatplugin.sf.net/update/content.xml. Received fatal alert: handshake_failure
    Graphviz--图形绘制工具
    使用Maven+Nexus+Jenkins+Svn+Tomcat+Sonar搭建持续集成环境
    MySQL在并发场景下的问题及解决思路
    MIT KIT OpenID Connect Demo Client
  • 原文地址:https://www.cnblogs.com/HJiang/p/7545750.html
Copyright © 2020-2023  润新知