iOS 9中NSURLConnection已被弃用。

5

我升级到了IOS9的xcode,但是我的获取webservice答案的方法失效了,这部分代码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");
}

2
转向NSURLSession - Adam
你们为什么已经放弃支持iOS 8了? - rmaddy
可能是重复的问题:NSURLSession/NSURLConnection在iOS 9上HTTP加载失败 - Gruntcakes
这个链接 https://dev59.com/Dl0a5IYBdhLWcg3wD1Pb 解决了我的问题,谢谢大家! - miguelzolk
2个回答

12

您实际的问题并不是NSURLConnection的用法,即使它已被弃用,iOS9也可以处理它。这里的问题在于您正在使用iOS9中苹果不鼓励使用的HTTP请求作为App Transport Security(ATS)的一部分。

根据苹果文档说明:

“App Transport Security (ATS) 通过应用和其后端之间安全连接执行最佳实践。ATS防止意外泄露,提供安全的默认行为,并易于采用;它在iOS 9和OS X v10.11中默认开启。无论您是创建新应用还是更新现有应用程序,都应尽快采用ATS。

如果您正在开发新应用程序,则应专门使用HTTPS。如果您有现有应用程序,则应立即尽可能多地使用HTTPS,并制定迁移其余应用程序的计划。此外,通过更高级别的API进行通信时,需要使用TLS版本1.2进行加密,并具有前向保密性。

如果您尝试建立不遵循此要求的连接,则会引发错误。如果您的应用程序需要向不安全域进行请求,您必须在应用程序的Info.plist文件中指定此域。

您可以通过将此键添加到项目的info.plist来绕过此问题。

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

stack overflow 链接和博客参考链接 iOS 9 ATS


2

废弃并不意味着某些东西不能使用。NSURLConnection在iOS9中仍然可用。

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

ATS == Apple传输安全。


我从未说过它会。无论原帖作者是否继续使用它,都与他们的问题无关。 - Gruntcakes
是的,有一个打字错误,所以它是不正确的。我只是在添加我的评论。谢谢你发现了这个问题。 - zaph

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接