Я использую NSURLSession
для разбора JSON. Я пишу такой код, но методы делегата не вызываются при запуске приложения. i.e connectionDidFinishLoading
и didReceiveData
методов. Как позвонить NSURLSessionDelegate
методов?NSURLSessionDelegate connectionDidFinishLoading метод не называется
-(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);
}
Добавить отформатированный код, так что каждый сможет прочитать код – Rajat
http://stackoverflow.com/ a/39203067/3400991 возможный дубликат –