2016-08-27 54 views
1

我遇到的問題是我的應用程序有一個線程,需要定期在循環內部發出一系列網絡請求。由於這是在一個單獨的線程內,並且由於請求的性質(對本地網絡上的設備並且響應很簡單),我想同步執行此操作。網絡通信是一個單獨的networking類比databaseController類。ios同步網絡請求處理程序返回結果

我不能得到networking類中的方法從完成處理

+ (void)GetMessages 
{ 
    NSURLSession *session = [NSURLSession sharedSession]; 
    NSURLRequest *request = [networking makeAuthenticatedRequest:@"subpath.html"]; 
    //NSString* returnable; 
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request 
            completionHandler: 
           ^(NSData *data, NSURLResponse *response, NSError *error) { 
            NSString* newStr = [[NSString alloc] initWithData:data 
                 encoding:NSUTF8StringEncoding]; 
            //returnable = newStr; 
            //return(newStr) 
            NSLog(newStr); 
           }]; 
    [task resume]; 
} 

上面的代碼工作,但裏面有返回值的功能只是打印請求的結果什麼。當我嘗試任何註釋掉的附加內容和必要的更改時,什麼都不起作用。我甚至試圖傳遞一個對調用對象的引用,並在完成處理程序中更新一個用於存儲newStr的屬性,但即使這樣也行不通。

是我想要的嗎?如果是這樣如何?

我應該補充說,代碼需要與ios 7-9兼容。

回答

1

你需要做到以下幾點:

NSURLSession *session = [NSURLSession sharedSession]; 
NSMutableURLRequest *request = 
[NSMutableURLRequest requestWithURL:[NSURL 
            URLWithString:@"https://www.yahoo.com"] 
       cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData 
        timeoutInterval:10 
]; 

__block NSString* returnable; // notice the __block here 
NSURLSessionDataTask *task = [session dataTaskWithRequest:request 
       completionHandler: 
       ^(NSData *data, NSURLResponse *response, NSError *error) { 
       NSString* newStr = [[NSString alloc] initWithData:data 
            encoding:NSUTF8StringEncoding]; 
       returnable = newStr; 
       // return(newStr); You cant return this here. Because the callback doesn't permit you to do so. 
       NSLog(@"%@", newStr); 
     }]; 
[task resume]; 
相關問題