[英]Refactoring my code for asynchronous NSURLConnection
使用同步請求時出現問題。 問題是我不確定如何重構下面的代碼來使用異步請求來完成以下兩個任務:
UIActivityIndicatorView
子視圖通知活動提取; Reachability
檢查,以確保存在Internet連接並且主機可用,即reachabilityWithHostName:@"wwww.mywebhostingisterrible.com"
。 目前我有一個帶有+(Fetcher *)sharedFetcher
單例的Fetcher
類,它在我的所有視圖控制器中用於獲取數據。 目前,使用以下代碼獲取所有數據:
- (NSString *)stringWithUrl:(NSURL *)url {
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
獲取的方法如下所示:
-(NSArray *)fetchDogFoodListing {
NSString *urlString = [NSString stringWithFormat:@"%@query/dogFood/%@/%lli/%@/%@",self.connectionUrl,self.queryCriteria.dogFoodName,self.queryCriteria.dogFoodBrandId,self.queryCriteria.dogFoodIngredients,self.queryCriteria.dogFoodBrand];
NSString *json = [self stringWithUrl:[NSURL URLWithString:urlString]];
return [self.factory buildIKDogFoodArrayWithJSON:json];
}
和來自UIViewController
的調用-(void)viewDidLoad
如下所示:
self.dogFoods = [[IKFetcher sharedFetcher] fetchDogFoodListing];
我考慮過在這種情況下實施代表,但我對代表團的工作方式非常不滿意。 我甚至不確定應該走哪條路。 如果Fetcher
有一個FetcherDelegate
可以通知視圖控制器何時完成,那么UI可以更新嗎? 視圖控制器是否應該有一個委托,以便在完成任務時獲取器可以更新視圖?
我肯定根據我的問題,你可以看到我對代表團的經驗不足,所以我很感激任何幫助。
你可能想看看Mugunth Kumar的精彩框架:
http://blog.mugunthkumar.com/products/ios-framework-introducing-mknetworkkit
我打算在未來的項目中使用它來進行NSURLConnection
你可以這樣做
dispatch_async(queue, ^{
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
//.. do stuff with data here...
}
}
或者您可以在dispatch_sync中執行sendSynchronousRequest代碼,如果您希望連接是同步的,盡管您應該盡可能地保持異步。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.