【问题标题】:Swift 2 Rest API not executing session.dataTaskWithRequestSwift 2 Rest API 不执行 session.dataTaskWithRequest
【发布时间】:2016-02-09 19:44:17
【问题描述】:

对 Swift 来说相当陌生。尝试执行简单的 REST API 提取。我在代码中没有收到任何错误,但是当我在调试模式下查看代码时 session.DataTaskWithRequest 似乎没有执行。

<code>
class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    let requestURL: NSURL = NSURL(string: "http://www.learnswiftonline.com/Samples/subway.json")!
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(urlRequest, completionHandler: {(data, response, error) -> Void in

        guard let responseData = data else {
            print("Error: did not receive data")
            return
        }
        guard error == nil else {
            print("error calling GET on /posts/1")
            print(error)
            return
        }
        let httpResponse = response as! NSHTTPURLResponse
        let statusCode = httpResponse.statusCode

        if (statusCode == 200) {
            print("Everyone is fine, file downloaded successfully.")
        }
    })

    task.resume()
    // Do any additional setup after loading the view, typically from a nib.
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
}
</code>

我可以毫无问题地在浏览器中点击 url,我什至尝试过其他测试 url。

有什么想法吗?

【问题讨论】:

    标签: xcode rest swift2 ios9


    【解决方案1】:

    我检查了代码,它对我有用。

    问题是您需要启用App Transport Security 才能访问iOS 9.0 及更高版本中的HTTP 调用。请查看以下步骤,了解如何将其添加到应用程序中。

    只需右键单击 .plist 文件 -> 打开为 -> 源代码并添加 下面的代码在里面。

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

    或者,如果您想应用于所有 URL。

    <key>NSAppTransportSecurity</key>
    <dict>
      <!--Include to allow all connections-->
      <key>NSAllowsArbitraryLoads</key>
          <true/>
    </dict>
    

    更多信息请参考苹果Info.plist reference

    希望对你有用!!!

    【讨论】:

      猜你喜欢
      • 2017-05-13
      • 2013-09-10
      • 1970-01-01
      • 2018-12-12
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多