這種異步性質讓我失望。從NSURLSession中返回數據completionHandler
我正在創建一個我可以在我的應用程序中使用的類。在這個類中,我有多個用於多個後端API的URL(a.com/A a.com/B等)。讓我們叫這個類NwrkDriver
@implementation NwrkDriver: NSObject
// Data is already formatted into a JSON doc.
- (int)PostToServer:(NSString *)url WithData:(NSData *)postData
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url] ];
[request setHTTPMethod:@"POST"];
<snip> deleted code for readability </snip>
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest
completionHandler
{
// Handle response here
// Where to put response obtained here?
}];
[uploadTask resume];
return 0;
}
- (int) DoAPI_A_WithData: (NSData *)data AndResult: (NSData *)result
{
NSString *url = "https://example.com/A";
[ self PostToServer:url WithData:data];
// How to populate results here?
}
@end
我想在代碼的其他類中使用此NwrkDriver。所以理想情況下,如果我想登錄,我將在NwrkDriver類中創建登錄API調用,並用適當的數據調用它。所以在登錄類
@implementation Login: NSObject
{
- (int) doLogin
{
NwrkDriver *nwrk = [[NwrkDriver alloc] init]
NSData *req, *response;
<snip> deleted code for readability </snip>
[nwrk DoAPI_A_WithData:req AndResult: response];
// Now parse the response which is JSON also
}
}
看起來我正在寫/思考在串行執行方面,這不是。
由於NSURLSession的異步特性,人們如何處理像auth這樣的調用,或者只是簡單地對後端進行reqeust/response?它們都必須在自然界中異步?如果是這樣,我該怎麼辦呢?
[在Swift/Objective C中如何從HTTP請求中返回數據](http://stackoverflow.com/questions/24784793/how-return-data-from-an-http-request-in-swift -objective-c) – SmokeDispenser
查看* Related *列,有幾個解決方案。 – vadian