2015-04-17 99 views
-2

我试图抓取一个iOS发送给我的服务器的URL生成的参数。 iOS运行一个线程异步获取参数。问题是,当我在我的主线程中为我的URL创建参数时,iOS async_param有时不包含在我需要的参数字典中(因为iOS尚未完成其线程)。处理异步生成的参数iOS8参数的最佳方式是什么?

例如,如果我试图生成包括来自两个不同的线程参数就应该是这样的http://myserver.com?param=my_param&async_param=my_async_param URL请求。要生成此我使用以下代码:

-(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上,处理这种情况的最佳方法是什么?

+2

何不而不是只是在块的结尾调用[self sendURLWithParamters:params]而不是?这样,只有在assign_param存在时才发送URL。 – rocky

+0

所以我忘了提到的一件事就是这个iOS类只在iOS8上可用。因此,如果它没有该类,它将无法发送ping。 – locoboy

+1

这是一个完全不同的问题,而不是我们正在讨论的问题。请为此提出一个新问题。 – rocky

回答

1

你或许应该创建一个错误/失败/无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 
    [[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]; 
    }]; 
} 
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 
} 
+0

Hrm - 这看起来非常有趣。这些工作如何? – locoboy

相关问题