IOS 9 NSURLConnection已弃用

我升级到IOS9 xcode,而我不工作的方法获得我的web服务的答案,这部分NSData * urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 已弃用。

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/index.html#//apple_ref/doc/uid/TP40003755

NSString *post =[[NSString alloc] initWithFormat:@"lang=%@&type=ssss",@"en"]; NSURL *url=[NSURL URLWithString:@"http://www.xxxxxxxxxx.com/xxxxxxx/ws/get_xxxxx.php"]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSLog(@"esta es la url: %@", postData); NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSError *error = [[NSError alloc] init]; NSHTTPURLResponse *response = nil; NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if ([response statusCode] >=200 && [response statusCode] <300) { NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:urlData options:kNilOptions error:&error]; NSInteger success = [(NSNumber *) [jsonData objectForKey:@"success"] integerValue]; if(success == 1) { if (self.lugares != nil) { self.lugares = nil; } self.lugares = [[NSMutableArray alloc] initWithArray:[jsonData objectForKey:@"lugares"]]; } else { NSLog(@"no hay datos :C"); } } else { NSLog(@"No encontrado"); } 

你的实际问题不是NSURLConnection的使用ios9会处理它,即使它被depricated,在这里,你使用从ios9苹果的HTTP请求的问题,阻止使用HTTP请求作为应用程序传输安全(ATS)的一部分,

从Apple文档:

“应用程序传输安全(ATS)强制执行应用程序与其后端之间的安全连接的最佳实践,ATS防止意外泄露,提供安全的默认行为,并且易于采用;在iOS 9和OS X中也是默认的v10.11。您应该尽快采用ATS,无论您是创build新应用程序还是更新现有应用程序。

如果您正在开发新的应用程序,则应该专门使用HTTPS。 如果您有现有的应用程序,则应尽可能使用HTTPS,并尽快制定一个计划来迁移应用程序的其余部分。 此外,通过更高级别的API进行的通信需要使用TLS 1.2版进行encryption,并具有正向保密性。

如果您尝试build立不符合此要求的连接,则会引发错误。 如果您的应用需要向不安全域发出请求,则必须在应用的Info.plist文件中指定此域。

您可以通过将此密钥添加到项目的info.plist中来绕过此操作

 <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> 

堆栈溢出链接和博客引用链接ios9 ATS

弃用并不意味着不起作用。 NSURLConnection仍然适用于iOS9。

你的问题是你使用的是HTTP,在iOS9中你应该使用HTTPS。 切换到HTTPS(推荐)或禁用ATS。

ATS ==苹果传输安全。