美文网首页
'sendSynchronousRequest:returnin

'sendSynchronousRequest:returnin

作者: 想飞的菜鸟 | 来源:发表于2020-10-12 16:31 被阅读0次

'sendSynchronousRequest:returningResponse:error:' is deprecated: first deprecated in iOS 9.0 - Use [NSURLSession dataTaskWithRequest:completionHandler:]

NSURLConnection 中的同步请求
NSURLConnection 中有一个同步请求的 API :

  • (NSData *)sendSynchronousRequest:(NSURLRequest *)request
    returningResponse:(NSURLResponse **)response
    error:(NSError **)error

使用Dispatch_semaphore(信号量)实现请求同步
信号量机制,我们可以简单理解为资源管理分配的一种抽象方式。在 GCD 中,提供了以下这么几个函数,可用于请求同步等处理,模拟同步请求:

dispatch_semaphore_t semaphore = dispatch_semaphore_create(value);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_semaphore_signal(semaphore);

            NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:contentModel.content]];
            __block NSData *imageData = [[NSData alloc] init];
            //创建信号量
            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
            NSURLSession *session = [NSURLSession sharedSession];
            NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                imageData = data;
                dispatch_semaphore_signal(semaphore);   //发送信号
            }];
            [task resume];
            //等待
            dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
            if (imageData) {
                attchImage.image = [UIImage imageWithData:imageData];
            }

相关文章

网友评论

      本文标题:'sendSynchronousRequest:returnin

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