簡體   English   中英

重構我的異步NSURLConnection代碼

[英]Refactoring my code for asynchronous NSURLConnection

使用同步請求時出現問題。 問題是我不確定如何重構下面的代碼來使用異步請求來完成以下兩個任務:

  1. 使用UIActivityIndicatorView子視圖通知活動提取;
  2. 在連接請求之前實施可訪問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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM