将 NSAllowsArbitraryLoads 添加到 plist 仍然无法正常工作

Adding NSAllowsArbitraryLoads to plist Still Not Working

我在另一台机器上有一个创建 JSON 的 PHP 文件,我想从 iOS 应用程序中获取它。

我尝试使用 IP 地址从 iOS 应用程序与 NSURL

连接
NSURL *url = [NSURL URLWithString:@"http://192.168.xx.xxx/JSON/JSONtoIOS.php"];
NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];  

然后,我在 info.plist 文件中添加了以下代码:

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

但是,我仍然收到相同的错误消息:

Transport security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

URL 在网络浏览器上打开正常,但 NSData 返回 nil 时出现问题。

谁能帮我解决这个问题?

编辑:在 (void)viewDidLoad

中使用 NSURLSession
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"http://192.168.xx.xxx/JSON/JSONtoIOS.php"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"%@", json);
}];
[dataTask resume];

首先应该是Info.plist。文件系统在 iOS 上区分大小写。只是挑剔——我怀疑这是你的问题。 :-)

其次,确保您将其添加到 Info.plist 中的正确位置。它必须在顶层。

第三,如果此应用包含任何应用扩展、框架或任何其他可能包含 Info.plist 文件的内容,请确保您正在编辑正确的 Info.plist 文件。

第四,确保你之后重建了你的应用程序,并且你确实是 运行 重建的副本。

第五,如果这没有帮助,请启用 CFNetwork 诊断日志记录,如 QA1887 中所述。

试试这个,

NSData *postData = [someStringToPost dataUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString:someURLString];

我想这就是问题所在。

希望对您有所帮助。

问题出在这一行:

NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];

那不是你建立网络的方式!这是对 dataWithContentsOfURL 的误用(它用于打开本地文件 URL),而且它是同步的,所以即使你在联网,你也会做坏事。

使用NSURLSession 通过数据任务获取数据。现在您的 NSAppTransportSecurity 设置将被遵守(此外,随着网络的进行,您将获得更好的信息)。