已弃用:iOS9中的“sendAsynchronousRequest:queue:completionHandler:”

我有我自己的类来进行http调用,但现在在iOS9中,此方法已被弃用:

[NSURLConnetion sendAsynchronousRequest:queue:completionHandler:]

我试图testing新的[NSURLSession dataTaskWithRequest:completionHandler:]

但Xcode提供了一个错误,因为它没有find这个方法。

Xcode编译器警告与不推荐的行:

  'sendAsynchronousRequest:queue:completionHandler:' is deprecated: first deprecated in iOS 9.0 - Use [NSURLSession dataTaskWithRequest:completionHandler:] (see NSURLSession.h 

新方法错误:

 No known class method for selector 'dataTaskWithRequest:completionHandler:' 

方法:

 -(void)placeGetRequest:(NSString *)action withHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *error))ourBlock { NSString *url = [NSString stringWithFormat:@"%@/%@", URL_API, action]; NSURL *urlUsers = [NSURL URLWithString:url]; NSURLRequest *request = [NSURLRequest requestWithURL:urlUsers]; //[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock]; [NSURLSession dataTaskWithRequest:request completionHandler:ourBlock]; } 

任何想法?

dataTaskWithRequest:completionHandler:是一个实例方法,而不是一个类方法。 您必须configuration新的会话或使用共享的会话:

 [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:ourBlock]; 
 [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) { // Block Body }]; 

如果您正在使用AFNetworking库,则可以使用会话,然后设置为在后台支持请求。 使用这种方法我解决了两个问题:

1)AFNetworking方法不被弃用

2)即使应用程序在状态背景之间进行请求处理

我希望这有助于类似的问题。 这是一个替代scheme。

 -(void) pingSomeWebSite { NSString* url = URL_WEBSITE; // defines your URL to PING NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setHTTPMethod:@"GET"]; [request setURL:[NSURL URLWithString:url]]; request.timeoutInterval = DEFAULT_TIMEOUT; // defines your time in seconds NSTimeInterval today = [[NSDate date] timeIntervalSince1970]; NSString *identifier = [NSString stringWithFormat:@"%f", today]; NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:identifier]; sessionConfig.timeoutIntervalForResource = DEFAULT_TIMEOUT_INTERVAL; // interval max to background __block AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration: sessionConfig]; NSURLSessionTask *checkTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { NSLog(@"- Ping to - %@", URL_WEBSITE); NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; dispatch_async(dispatch_get_main_queue(), ^(){ [manager invalidateSessionCancelingTasks:YES]; // LOGIC FOR RESPONSE CODE HERE }); }]; [checkTask resume]; } 
 let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in // Code } task.resume()