【发布时间】:2016-03-18 04:05:29
【问题描述】:
嗨,我是 ios 的初学者,当我们使用 NSURLRequest 调用服务时,我想知道当我们使用“同步请求”调用服务并以编程方式使用异步请求调用服务时会发生什么, 请以编程方式解释操作,我在下面使用该代码编写了一些代码解释同步和异步操作
我的代码:-
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"http://api.kivaws.org/v1/loans/search.json?status=fundraising"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:@"GET"];
[theRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[theRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[theRequest setTimeoutInterval:5];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(connection){
webData = [[NSMutableData alloc] init];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[webData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"error is %@",[error localizedDescription]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString * allDataDictionbary = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSArray * responseString = [allDataDictionbary JSONValue];
NSLog(@"final respone dictionary%@",responseString);
}
【问题讨论】:
-
重新同步请求和异步请求的区别,见stackoverflow.com/q/21122842/1271826。关于此代码示例,这是一个异步请求,这很好,因为您不想从主线程发出同步请求。事实上,同步网络请求是个糟糕的主意,新的
NSURLSession取代了您在代码示例中使用的已弃用的NSURLConnection,甚至不提供同步再现。 -
嗨@Rob我是Ios的初学者,你说根本不再使用NSURLConnection。使用 NSURLSession 我该如何使用,请更新我的代码
标签: ios objective-c nsurlconnection