【发布时间】:2016-12-14 06:49:05
【问题描述】:
我正在使用NSURLSession 进行 JSON 解析。我正在编写这样的代码,但是当我运行应用程序时没有调用委托方法。即connectionDidFinishLoading 和didReceiveData 方法。如何调用NSURLSessionDelegate方法?
-(void)viewDidLoad {
[super viewDidLoad];
menuArr = [[NSMutableArray alloc]init];
self.view.backgroundColor = [UIColor whiteColor];
NSURL *url =[NSURL URLWithString:@"http://url"];
dataTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data,NSURLResponse *response,NSError *error)
{
if(error == nil)
{
NSError *JSONError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&JSONError];
NSLog(@"Dictionary is:%@",dictionary);
}
}];
[dataTask resume];
}
#pragma mark - NSURLSession delegate methods
- (BOOL)URLSession:(NSURLSession *)session dataTask:(NSURLSessionTask *)dataTask canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace*)protectionSpace
{
BOOL isvalue = [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
return isvalue;
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,NSURLCredential *credential))completionHandler
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)aresponse
{
receivedData = [[NSMutableData alloc]init];
[receivedData setLength:0];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Received String %@",str);
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionTask *)dataTask connectionDidFinishLoading:(NSURLConnection *)conn
{
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];
NSString *str=[dict objectForKey:@"Status"];
NSLog(@"Status Response is:%@",str);
NSDictionary *jsonDict = [dict valueForKey:@"data"];
NSLog(@"Json Dictionary is:%@",jsonDict);
menuArr = [jsonDict valueForKey:@"Text"];
NSLog(@"Item Name is:%@",menuArr);
}
【问题讨论】:
-
添加格式化代码,以便所有人都能阅读您的代码
标签: ios objective-c cocoa-touch nsurlsession