gpt4 book ai didi

ios - NSURLConnection 的 didReceiveData 在 dispatch_async block 中不起作用

转载 作者:行者123 更新时间:2023-12-01 18:51:56 25 4
gpt4 key购买 nike

我试图在通过 NSURLConnection 加载 URL 之前验证用户的 token 。

我的问题是,如果我在 dispatch_async 中启动 NSURLConnection block (见下面的 1),(NSURLConnection *)connection didReceiveData方法永远不会被调用。

1. 在新线程上调用token check的方法:

- (void)awaitTokenCheckCompletion:(void (^) (BOOL success))completion {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, kNilOptions), ^{

[self checkAccessTokenExpiration];

dispatch_async(dispatch_get_main_queue(), ^{
});
});
}

上面的代码调用 checkAccessTokenExpiration方法,它将触发 createClientCredentials下面的方法。

2. 创建NSURLConnection的方法:
-(void) createClientCredentials {
DLog("Getting Access Token");

NSString *post = [NSString stringWithFormat:@"type=get&id=%@&key=%@",@"id",@"key"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@authorization/keys", serverURL]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

__attribute__((unused))
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
}

3. (NSURLConnection *)connection didReceiveData 方法永远不会被调用:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
DLog("gotData");
}

最佳答案

您从文档中将委托(delegate)设置在 block 内

The delegate object for the connection. The connection calls methods on this delegate as the load progresses. Delegate methods are called on the same thread that called this method. For the connection to work correctly, the calling thread’s run loop must be operating in the default run loop mode.



因此,尝试将委托(delegate)设置在异步 block 之外

关于ios - NSURLConnection 的 didReceiveData 在 dispatch_async block 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30450325/

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