我正在尝试为我发送到服务器的URL抓取iOS生成的参数。 iOS运行线程异步以获取参数。问题是,当我在主线程中为我的URL创建参数时,iOS async_param
有时不包含在我需要的参数字典中(因为iOS尚未完成运行其线程)。
例如,如果我尝试生成包含来自两个不同线程的参数的URL请求,它应该看起来像http://myserver.com?param=my_param&async_param=my_async_param
。要生成它,我使用以下代码:
-(void) sendURL{
NSMutableDictionary *params = [NSMutableDictionary dictionary];
//this is my param in the main thread
[params setObject:@"my_param" forKey:@"param"];
//get my iOS async param
[[someIOS8Class sharedInstance] getAsyncParamWithCompletionHandler:^(NSString param)
{
[params setObject:param forKey:@"async_param"];
}];
[self sendURLWithParameters: params];
//this is where sometimes the async param does not show up in the URL
}
如果IOSClass仅存在于iOS8上,那么处理这种情况的最佳方法是什么?
答案 0 :(得分:1)
你应该创建一个错误/失败/无参数块然后发送网址
-(void) sendURL{
NSMutableDictionary *params = [NSMutableDictionary dictionary];
//this is my param in the main thread
[params setObject:@"my_param" forKey:@"param"];
//get my iOS async param
[[someIOSClass sharedInstance] getAsyncParamWithCompletionHandler:^(NSString param)
{
// send the parameter if there's an async param
[params setObject:param forKey:@"async_param"];
[self sendURLWithParameters: params];
} withFailure:^(NSError *error) {
//Create this error if there's no async param
[self sendURLWithParameters: params];
}];
}
答案 1 :(得分:0)
您可以使用信号量等待任何异步代码:
-(void)sendURL {
NSMutableDictionary *params = [NSMutableDictionary dictionary];
//this is my param in the main thread
[params setObject:@"my_param" forKey:@"param"];
//get my iOS async param
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[[someIOS8Class sharedInstance] getAsyncParamWithCompletionHandler:^(NSString param) {
[params setObject:param forKey:@"async_param"];
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
[self sendURLWithParameters: params];
dispatch_release(semaphore);
//this is where sometimes the async param does not show up in the URL
}