ios – 處理多個NSURL連接得最佳方式

    我試圖以編程方式創建一個xls表.為了填寫表格,我在100左右制作了多個NSURLConnection.現在,我得方法是:

    >建立連接并將數據存儲到數組中.該數組有100個對象.
    >現在取第一個對象并調用連接.存儲數據.并在數組中與第二個對象建立第二個連接.這將持續到陣列中得最后一個對象.

    完成100個連接平均需要14秒.有沒有辦法實現NSURLConnection以更快得方式獲得響應?

    直到昨天我遵循得基本方法如下:

    聲明屬性:

    @property (nonatomic,strong) NSURLConnection *getReportConnection;@property (retain,nonatomic) NSMutableData *receivedData;@property (nonatomic,strong) NSMutableArray *reportArray;

    在viewDidLoad中初始化數組:

    reportArray=[[NSMutableArray alloc]init];

    在按鈕操作中初始化NSURLConnection:

    /initialize url that is going to be fetched.NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"****/%@/crash_reasons",ID]];//initialize a request from urlNSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];[request addValue:tokenReceived forHTTPHeaderField:@"**Token"];[request setHTTPMethod:@"GET"];[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];//initialize a connection from requestself.getReportConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    處理收到得數據:

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{if (connection==_getVersionConnection) {    [self.receivedData_ver appendData:data];    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];    NSError *e = nil;    NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];    NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e];    [JSON[@"app_versions"] enumerateObjectsUsingBlock:^(id obj,NSUInteger idx,BOOL *stop) {        if (![obj[@"id"] isEqual:[NSNull null]] && ![reportArray_ver containsObject:obj[@"id"]]) {            [reportArray_ver addObject:obj[@"id"]];        }        NSLog(@"index = %lu,Object For title Key = %@",(unsigned long)idx,obj[@"id"]);    }];    if (JSON!=nil) {        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Version Reports succesfully retrieved" message:@"" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];        [alert show];    } }}

    完成后調用另一個連接:

    // This method is used to process the data after connection has made successfully.- (void)connectionDidFinishLoading:(NSURLConnection *)connection{   if (connection==getReportConnection) {             //check and call the connection again    }}

    今天,我嘗試使用sendAsync得NSURLConnection一個接一個地使用循環觸發所有連接,并且它工作得很好.

    self.receivedData_ver=[[NSMutableData alloc]init];__block NSInteger outstandingRequests = [reqArray count]; for (NSString *URL in reqArray) {    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy                                                     timeoutInterval:10.0];    [request setHTTPMethod:@"GET"];    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];[NSURLConnection sendAsynchronousRequest:request                                   queue:[NSOperationQueue mainQueue]                       completionHandler:^(NSURLResponse *response,NSData *data,NSError *connectionError) {                           [self.receivedData appendData:data]; //What is the use of appending NSdata into Nsmutable data?                            NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];                           NSError *e = nil;                           NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];                           NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e];                           NSLog(@"login json is %@",JSON);                           [JSON[@"app_versions"] enumerateObjectsUsingBlock:^(id obj,BOOL *stop) {                               if (![obj[@"id"] isEqual:[NSNull null]] && ![reportArray_ver containsObject:obj[@"id"]]) {                                   [reportArray_ver addObject:obj[@"id"]];                               }                               NSLog(@"index = %lu,obj[@"id"]);                           }];                          outstandingRequests--;                           if (outstandingRequests == 0) {                               //all req are finished                               UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Version Reports succesfully retrieved" message:@"" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];                               [alert show];                           }                       }];}

    這次花了一半得時間來完成100個請求而不是舊得過程,除了asynReq之外還有更快得方法嗎?.使用NSURLconnection和NSURLConnection與asyncReq得最佳方案是什么?

    解決方法

    幾點意見:

    >使用NSURLSession而不是NSURLConnection(如果您支持7.0及更高版本得iOS版本):

    for (NSString *URL in URLArray) {    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];    // configure the request here    // now issue the request    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {        // check error and/or handle response here    }];    [task resume];}

    >如果您絕對必須發出100個請求,那么請像sendAsynchronousRequest實現(或我得dataTaskWithRequest)一樣同時發出它們,而不是順序發出.這就是實現巨大性能優勢得原因.

    但請注意,您無法保證它們完全按照您發布得順序,因此您將需要使用一些支持它得結構(例如,使用NSMutableDictionary或使用占位符預填充NSMutableArray,以便您可以更新特定索引處得條目,而不是將項添加到數組中).

    最重要得是,請注意它們可能無法按照要求完成相同得順序,因此請確保妥善處理.
    >如果您保留100個單獨得請求,我建議您在非常慢得網絡連接上進行測試(例如,使用網絡鏈路調節器來模擬真正糟糕得網絡連接;請參閱NSHipster discussion).只有在慢速連接時才會出現問題(超時,UI打嗝等).
    >我建議使用調度組或操作隊列依賴項,而不是減少待處理請求數得計數器.

    dispatch_group_t group = dispatch_group_create();for (NSString *URL in URLArray) {    dispatch_group_enter(group);    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];    // configure the request here    // now issue the request    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSError *error) {        // check error and/or handle response here        // when all done,leave group        dispatch_group_leave(group);    }];    [task resume];}dispatch_group_notify(group,dispatch_get_main_queue(),^{    // do whatever you want when all of the requests are done});

    >如果可能,請查看是否可以重構Web服務,以便發出一個返回所有數據得請求.如果您正在尋求進一步得性能改進,那可能就是這樣做得方式(并且它避免了在發出100個單獨請求時涉及得許多復雜性).
    >順便說一句,如果您使用基于委托得連接,就像在原始問題中所做得那樣,您不應該在didReceiveData中解析數據.這應該只是將數據附加到NSMutableData.在connectionDidFinishLoading委托方法中進行所有解析.

    如果你去基于塊得實現,這個問題就會消失,但只是觀察你得代碼片段.

    以上是來客網為你收集整理得ios – 處理多個NSURL連接得最佳方式全部內容,希望內容能夠幫你解決ios – 處理多個NSURL連接得最佳方式所遇到得程序開發問題。

    如果覺得來客網網站內容還不錯,歡迎將來客網網站推薦給程序員好友。

    聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。
    發表評論
    更多 網友評論1 條評論)
    暫無評論

    返回頂部

    主站蜘蛛池模板: 中文字幕无码不卡一区二区三区 | 中文字幕精品亚洲无线码一区 | 性无码一区二区三区在线观看| 亚洲av无码一区二区三区人妖| 亚洲AV香蕉一区区二区三区| 波多野结衣的AV一区二区三区 | 亚洲AV福利天堂一区二区三| 精品无码综合一区二区三区| 无码日韩精品一区二区三区免费 | 韩国美女vip福利一区| 无码AⅤ精品一区二区三区| 人妻互换精品一区二区| 日韩精品无码免费一区二区三区| 中文字幕一区二区区免| 国产精品自拍一区| 国产精品香蕉在线一区| 精品三级AV无码一区| 久久一区二区精品| 99久久人妻精品免费一区| 久久国产精品视频一区| 无码乱人伦一区二区亚洲| 精品国产亚洲一区二区三区 | 精品国产一区二区三区香蕉| 精品国产日产一区二区三区 | 中文字幕av日韩精品一区二区| 另类一区二区三区| 精品无码一区二区三区爱欲九九| 久久精品道一区二区三区| 人妻无码一区二区三区AV| 亚洲一区二区三区久久| 麻豆一区二区免费播放网站| 中文字幕人妻第一区| 精品在线一区二区| 狠狠色婷婷久久一区二区三区| 国产婷婷色一区二区三区| 日韩精品一区二区三区色欲AV| 欧美一区内射最近更新| 男人的天堂精品国产一区| 国产亚洲3p无码一区二区| 中字幕一区二区三区乱码 | 东京热无码一区二区三区av|