Tôi đang cố gắng tạo một bảng xls theo lập trình. Để điền vào trang tính, tôi đang tạo số nhiều NSURLConnection
khoảng 100. Hiện tại, cách tiếp cận của tôi là:Cách tốt nhất để xử lý nhiều kết nối NSURL
- Tạo kết nối và lưu trữ dữ liệu vào một mảng. Mảng này có 100 đối tượng.
- Bây giờ lấy đối tượng đầu tiên và gọi kết nối. Lưu trữ dữ liệu. Và tạo kết nối thứ hai với đối tượng thứ 2 trong mảng. Điều này tiếp tục cho đến khi đối tượng cuối cùng trong mảng.
Mất trung bình 14 giây để hoàn thành 100 kết nối. Có cách nào để triển khai NSURLConnection
để nhận phản hồi nhanh hơn không?
Đến ngày hôm qua tôi đi theo cách tiếp cận cơ bản như:
Tuyên bố các thuộc tính:
@property (nonatomic,strong) NSURLConnection *getReportConnection;
@property (retain, nonatomic) NSMutableData *receivedData;
@property (nonatomic,strong) NSMutableArray *reportArray;
Khởi tạo mảng trong viewDidLoad
:
reportArray=[[NSMutableArray alloc]init];
Khởi tạo các NSURLConnection
trong một hành động nút:
/initialize url that is going to be fetched.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"****/%@/crash_reasons",ID]];
//initialize a request from url
NSMutableURLRequest *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 request
self.getReportConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Chế biến các dữ liệu nhận được:
- (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];
}
}
}
Gọi một kết nối sau một kết thúc:
// 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
}
}
Và hôm nay, tôi đã thử NSURLConnection
với sendAsync
để bắn tất cả các kết nối một sau khi sử dụng vòng lặp khác và nó hoạt động khá tốt.
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, 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"]);
}];
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];
}
}];
}
Lần này phải mất một nửa thời gian để hoàn thành 100 yêu cầu hơn so với quy trình cũ, Có cách nào nhanh hơn tồn tại khác với asynReq? .What kịch bản tốt nhất để sử dụng NSURLconnection
và NSURLConnection with asyncReq
là?
Tại sao không sử dụng NSURLSession? NSURLConnection hiện không được chấp nhận –