我正在使用https://xx.app.goo.gl/?link=http%3A%2F%2Fxx.com%2F%3Fusn%3Dabc%26pass%3Ddef&apn=com.xx&afl=http://google.com
进行JSON解析。我正在编写这样的代码,但在运行应用程序时不会调用委托方法。即NSURLSession
和connectionDidFinishLoading
方法。如何调用didReceiveData
方法?
NSURLSessionDelegate
答案 0 :(得分:0)
您正在使用共享会话。这是一个没有委托的预先存在的会话。如果您希望任务调用委托方法,则必须:
答案 1 :(得分:0)
添加此两个代表 NSURLSessionDelegate,NSURLSessionDataDelegate
-(void)viewDidLoad {
[super viewDidLoad];
[self sendHTTPPost];
}
-(void) sendHTTPPost
{
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];
NSURL * url = [NSURL URLWithString:@"http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo"];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod:@"POST"];
NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:urlRequest];
[dataTask resume];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
{
NSLog(@"### handler 1");
completionHandler(NSURLSessionResponseAllow);
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@" dict=>> %@",dict);
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
if(error == nil)
{
NSLog(@"Download is Succesfull");
}
else
NSLog(@"Error %@",[error userInfo]);
}
答案 2 :(得分:-1)
您必须在类定义附近编写委托方法;
样品:
@interface MyControllerClass:<>中的UIViewController UIAlertViewDelegate