我已升级到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也会处理它,这是您从ios9使用的http请求的问题苹果不鼓励将HTTP请求用作应用程序传输安全性(ATS)的一部分
来自Apple文档:
您可以通过将此 key 添加到项目的info.plist
中来绕过此操作
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
stack overflow link和博客引用链接
ios9 ATS