【问题标题】:Strange (bug ?) with Xcode 7 / iOS 9 b5 with dataWithContentsOfURL带有 dataWithContentsOfURL 的 Xcode 7 / iOS 9 b5 奇怪(错误?)
【发布时间】:2015-11-01 09:54:57
【问题描述】:

我有一部分代码在所有 iOS 版本上都能按预期工作,但在 iOS 9 上却不行:

NSData *response = [NSData dataWithContentsOfURL: [NSURL URLWithString: url] options:NSDataReadingUncached error:&error];

这是一个简单的 json 文本。

我收到了这个错误:

Error Domain=NSCocoaErrorDomain Code=256 "无法打开文件“xxx.php”。"用户信息={NSURL=http://xxx.xxx.com/xxx/xxx.php?lang=fr}

如何将这个 url 解释为一个文件?响应 = 无...

谢谢。

【问题讨论】:

  • 在苹果论坛上发布问题。
  • 我要求确保我不会遗漏任何东西(例如:https 自 iOS 9 起强制使用)

标签: ios xcode7 ios9


【解决方案1】:

技术上是因为iOS9中网络的NSURLSession的变化。 要解决您的问题,您需要转到应用程序的 info.plist,NSAppTransportSecurity [Dictionary] 需要将密钥 NSAllowsArbitraryLoads [Boolean] 设置为 YES 或使用 https 调用 url。

更多iOS9中网络NSURLSession的变化可以在http://devstreaming.apple.com/videos/wwdc/2015/711y6zlz0ll/711/711_networking_with_nsurlsession.pdf?dl=1看到

【讨论】:

  • C&P版本:<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>
  • 不要这样做!如果你这样做,你基本上是在破坏 iOS9 中引入的“App Transport Security”的附加安全功能。而是看到这个答案:stackoverflow.com/a/30836686/505093
【解决方案2】:

调试了 3 个小时后,我通过使用异步 NSMutableURLRequest 完全避免了这个错误,我还观察到它比同步 NSData 快得多。

let requestURL: NSURL = NSURL(string: url)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
    (data, response, error) -> Void in
    if error == nil {
        var response = UIImage(data:data!)
    } else {
        NSLog("Fail")
    }
}
task.resume()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 2018-06-27
    相关资源
    最近更新 更多