gpt4 book ai didi

ios - 如何等待完成 dataTaskWithRequest?

转载 作者:可可西里 更新时间:2023-11-01 06:20:03 24 4
gpt4 key购买 nike

如何等待 dataTaskWithRequest 完成?网络抓取完全结束后,我需要执行一些任务。

最佳答案

如果确实需要同步请求,可以使用信号量

我在 NSURLSession 上实现了一个小类来提供这个功能。

.h文件中:

@import Foundation.NSURLSession;

@interface NSURLSession (Additions)

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

@end

.m文件中:

@implementation NSURLSession (Additions)

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse *__autoreleasing *)responsePointer error:(NSError *__autoreleasing *)errorPointer
{
dispatch_semaphore_t semaphore;
__block NSData *result = nil;

semaphore = dispatch_semaphore_create(0);

void (^completionHandler)(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error);
completionHandler = ^(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error)
{
if ( errorPointer != NULL )
{
*errorPointer = error;
}

if ( responsePointer != NULL )
{
*responsePointer = response;
}

if ( error == nil )
{
result = data;
}

dispatch_semaphore_signal(semaphore);
};

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:completionHandler] resume];

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

return result;
}

@end

关于ios - 如何等待完成 dataTaskWithRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33148310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com