IOS 9 NSURLConnection已弃用

时间:2015-09-17 15:49:59

标签: ios objective-c web-services

我升级到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 个答案:

答案 0 :(得分:12)

你的实际问题不是NSURLConnection使用ios9会处理它,即使它也被删除,这里你从ios9苹果使用http请求的问题阻止使用HTTP请求作为App Transport Security(ATS)的一部分< / p>

来自Apple文档:

  

&#34;应用传输安全(ATS)在安全中实施最佳实践   应用程序与其后端之间的连接。 ATS防止意外   披露,提供安全的默认行为,易于采用;它   在iOS 9和OS X v10.11中默认也是打开的。你应该采用ATS   尽快,无论您是否正在创建新的应用程序   或更新现有的。

     

如果您正在开发新应用,则应该专门使用HTTPS。如果   你有一个现有的应用程序,你应该尽可能多地使用HTTPS   现在,并创建一个计划,以迁移您的应用程序的其余部分   尽快。另外,您通过更高层次的沟通   API需要使用具有前向保密性的TLS 1.2版进行加密。

     

如果您尝试建立不遵循此连接的连接   要求,抛出错误。如果您的应用需要提出请求   对于不安全的域,您必须在应用中指定此域   Info.plist文件。&#34;

您可以通过将此密钥添加到项目的info.plist

来绕过此问题
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

stack overflow link和博客参考链接 ios9 ATS

答案 1 :(得分:2)

不推荐并不意味着某些东西不起作用。 NSURLConnection仍可在iOS9中使用。

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

ATS == Apple Transport Security。