美文网首页程序员iOS 开发 iOS Developer
iOS学习 多线程与网络请求。

iOS学习 多线程与网络请求。

作者: 蠢萌的L君 | 来源:发表于2016-05-02 17:47 被阅读2536次

    多线程

    • NSThread
      • 最常用的用法为 [NSThread currentThread];查看当前线程
    • GCD
      • 队列
        • 并发队列
          • 全局队列dispatch_get_global_queue
          • 自己创建
        • 串行队列
          • 自己创建
          • 主队列dispatch_get_main_queue
      • 任务:block
      • 函数
        • sync:同步函数
        • async:异步函数
      • 单例模式
        • 重写allocWithZone(由于alloc会调用allocWithZone)
        • 重写copyWithZone(调用allocWithZone方法即可)
        • 提供shaer开头的类方法。
    • NSOperation
    • RunLoop
      • 同一时间只能选择一个模式运行
      • 自己开辟的子线程需要手动启用runloop
      • 模式下有source(事件源), NSTimer(定时器),observe(观察者)
      • 自己开辟的子线程必须添加事件源,或者定时器,启动runloop才不会停止。
      • 常用模式
        • Default:默认
        • Tracking:拖拽UIScrollView

    网络

    HTTP请求

    • GET请求
    // URL
    NSString *urlStr = @"http://xxxxx.com";
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    // 请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    • POST请求
    // URL
    NSString *urlStr = @"http://xxxxx.com";
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    // 请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [@"username=123&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];
    

    数据解析

    • JSON
      • NSJSONSerialization
    • XML
      • SAX: NSXMLParser
      • DOM: GDataXML

    NSURLConnection(iOS9已经过期)

    • 同步方法
    • 异步方法-block
    • 异步方法-代理

    NSURLSession

    • 发送一般的GET\POST请求
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    
    }];
    
    [task resume];
    
    • 下载文件 - 不需要离线断点
    NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    
    }];
    
    [task resume];
    
    • 下载文件 - 需要离线断点
    • 开启任务
    // 创建session
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    
    // 设置请求头(告诉服务器第1024个字节开始下载)
    [request setValue:@"bytes=1024-" forHTTPHeaderField:@"Range"];
    
    // 创建任务
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
    
    // 开始任务
    [task resume];
    
    • 实现代理方法
    - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
    {
        // 打开NSOutputStream
    
        // 获得文件的总长度
    
        // 存储文件的总长度
    
        // 回调
        completionHandler(NSURLSessionResponseAllow);
    }
    
    - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
    {
        // 利用NSOutputStream写入数据
    
        // 计算下载进度
    }
    
    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
    {
        // 关闭并且清空NSOutputStream
    
        // 清空任务task
    }
    
    • 文件上传
      • 设置请求头
      • 拼接请求体
        • 文件参数
        • 其他参数(非文件参数)
      • NSURLSessionUploadTask
    NSURLSessionUploadTask *task = [[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    
    }];
    
    [task resume];
    

    AFN

    • GET
    // AFHTTPSessionManager内部包装了NSURLSession
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    
    NSDictionary *params = @{
                             @"username" : @"520it",
                             @"pwd" : @"520it"
                             };
    
    [mgr GET:@"http://120.25.226.186:32812/login" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"请求成功---%@", responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"请求失败---%@", error);
    }];
    
    • POST
    // AFHTTPSessionManager内部包装了NSURLSession
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    
    NSDictionary *params = @{
                             @"username" : @"520it",
                             @"pwd" : @"520it"
                             };
    
    [mgr POST:@"http://120.25.226.186:32812/login" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"请求成功---%@", responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"请求失败---%@", error);
    }];
    
    • 文件上传
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    
    [mgr POST:@"http://120.25.226.186:32812/upload" parameters:@{@"username" : @"123"}
        constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 在这个block中设置需要上传的文件
    //            NSData *data = [NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/placeholder.png"];
    //            [formData appendPartWithFileData:data name:@"file" fileName:@"test.png" mimeType:@"image/png"];
    
    //            [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/xiaomage/Desktop/placeholder.png"] name:@"file" fileName:@"xxx.png" mimeType:@"image/png" error:nil];
    
            [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/xiaomage/Desktop/placeholder.png"] name:@"file" error:nil];
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"-------%@", responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
    
    }];
    

    UIWebView

    • 加载请求
    • JS和OC的互相调用
    • 利用NSInvocation实现performSelector无限参数
    • 异常捕捉
      • NSException
      • 崩溃统计(第三方)
        • 友盟
        • Flurry
        • Crashlytics

    相关文章

      网友评论

        本文标题:iOS学习 多线程与网络请求。

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