2015-04-17 104 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

相關問題