Swift 2 : NSData(contentsOfURL:url) 返回 nil

Swift 2 : NSData(contentsOfURL:url) returning nil

我有一个网页地址,其中包含一个 JSON 文件。我试图在 Swift 2 中将 JSON 文件作为 NSDictionary 访问。每次我调用 NSData(contentsOfURL:url!) 时,其中 urlNSURL? 的类型,它 returns nil。我正在使用 Xcode 7 Beta,该项目最初是在 Xcode 6.

中制作的

以下代码导致了问题。

let url = NSURL(string:myurl) // myurl is the webpage address.
let data = NSData(contentsOfURL:url!) // the bit that returns nil
// data is set to nil
// I would perform NSJSONSerialization.JSONObjectWithData later.

令我困惑的是,当我使用 swift 在终端中键入相同的代码时尝试完全相同的事情时,常量 data 未设置为零。我试过重新启动 Mac,但没有用。我尝试重新安装 Xcode,但没有成功。

这就是我使用 swift 关键字向终端输入以下代码时发生的情况。

$> swift
......
Welcome to Apple Swift version 2.0 (700.0.38.1 700.0.53). Type :help for assistance. 

1> import Foundation
2> var urlstr = "http://mywebsiteaddress/jsonfile.json"
3> var nsurl = NSURL(string:urlstr)
nsurl: NSURL? = "http://mywebsiteaddress/jsonfile.json"{
    ObjectiveC.NSObject = {...}
}
4> var nsdata = NSData(contentsOfURL:nsurl!)
nsdata: NSData? = 5925 bytes {
    ObjectiveC.NSObject = {...}
}
5> print(nsdata)
Optional(<Some Values..........>)

当我在终端中尝试时,它确实有效。谁能帮我解决问题??

我希望它能在终端中运行,因为您在这里看到的可能不是 Swift 或 Cocoa Touch 中的错误,而是新功能的副作用iOS 9 个叫 App Transport Security。这意味着默认情况下,iOS 将不允许您向未受 SSL 保护的服务器发出请求。

引自link:

App Transport Security (ATS) lets an app add a declaration to its Info.plist file that specifies the domains with which it needs secure communication. ATS prevents accidental disclosure, provides secure default behavior, and is easy to adopt. You should adopt ATS as soon as possible, regardless of whether you’re creating a new app or updating an existing one.

If you’re developing a new app, you should use HTTPS exclusively. If you have an existing app, you should use HTTPS as much as you can right now, and create a plan for migrating the rest of your app as soon as possible.

要解决此问题,您可以编辑 info.plist 文件以在逐个域的基础上创建例外,或完全禁用 App Transport Security。这是引用自 .

的示例
<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>yourserver.com</key>
    <dict>
      <!--Include to allow subdomains-->
      <key>NSIncludesSubdomains</key>
      <true/>
      <!--Include to allow insecure HTTP requests-->
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <!--Include to specify minimum TLS version-->
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>

尽管我建议您实际上不要将其用作您的解决方案,而是使用 SSL 安全 https URL。