【问题标题】:getting data from URL in Swift从 Swift 中的 URL 获取数据
【发布时间】:2016-02-16 07:26:52
【问题描述】:

我正在尝试从服务器下载 JSON 文件并按照教程执行此操作 (http://www.learnswiftonline.com/mini-tutorials/how-to-download-and-read-json/)

首先我尝试了“检查响应”部分(我添加了一些部分以查看问题所在)

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) {
    (data, response, error) -> Void in

        let httpResponse = response as! NSHTTPURLResponse
        let statusCode = httpResponse.statusCode

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

task.resume()

这应该打印“每个人都很好~”或“失败”,但都没有出现...我试图查看 statusCode,所以我将 print(statusCode) 放在 task 中,但仍然没有打印任何内容。

这是我的操场截图:

+

CFRunLoop in Swift Command Line Program

这是我一直在寻找的答案,因为我正在处理 OS X 命令行应用程序(我将整个团队搬到了操场上,看看会发生什么)。如果你和我一样,请检查这个

【问题讨论】:

  • 非常感谢您的编辑! :)

标签: ios json swift


【解决方案1】:

你看不到任何东西,因为dataTaskWithRequest 是异步的,并且你的 Playground 只是在 'task.resume()` 之后停止。异步任务无法运行更改。

你可以在最后调用这个,在task.resume之后:

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

还有'import XCPlayground',类似这样:

import Foundation
import XCPlayground

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) {(data, response, error) -> Void in

  let httpResponse = response as! NSHTTPURLResponse
  let statusCode = httpResponse.statusCode

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

}
task.resume()

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

这篇文章可能会澄清更多: How do I run Asynchronous callbacks in Playground

编辑:

在 Swift 3 中,这发生了一些变化。

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

【讨论】:

  • 哇,我一定早点问过了... :) 绝对有效。非常感谢!
【解决方案2】:

在我更改“http”后在我的项目中运行良好 -> https,Apple 宣布 iOS 9 和 OSX 10.11 El Capitan 的“App Transport Security”

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

        let httpResponse = response as! NSHTTPURLResponse
        let statusCode = httpResponse.statusCode

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

http 响应:

 <NSHTTPURLResponse: 0x7a670300> { URL: https://www.learnswiftonline.com/Samples/subway.json } { status code: 200, headers {
"Content-Encoding" = gzip;
"Content-Type" = "application/json";
Date = "Tue, 16 Feb 2016 07:43:05 GMT";
"Last-Modified" = "Sat, 14 Nov 2015 08:21:26 GMT";
Server = "cloudflare-nginx";
"Set-Cookie" = "__cfduid=d9d92befe8746168b2b291f5bfb8996081455608585; expires=Wed, 15-Feb-17 07:43:05 GMT; path=/; domain=.learnswiftonline.com; HttpOnly";
"cf-ray" = "27579e989ad5208a-KIX";

} }

如果使用http则错误

    Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSErrorFailingURLStringKey=http://www.learnswiftonline.com/Samples/subway.json, NSErrorFailingURLKey=http://www.learnswiftonline.com/Samples/subway.json, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection., NSUnderlyingError=0x7866de20 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多