>建立連接并將數據存儲到數組中.該數組有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連接得最佳方式所遇到得程序開發問題。
如果覺得來客網網站內容還不錯,歡迎將來客網網站推薦給程序員好友。