从Swift中的URL获取数据

时间:2016-02-16 07:26:53

标签: ios json swift

我试图从服务器&amp ;;下载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里面但是再没有打印出来。

这是我对游乐场的截图:

enter image description here

+

CFRunLoop in Swift Command Line Program

这是我正在寻找的答案,因为我正在处理OS X命令行应用程序(我把整个团队移动到游乐场看看会发生什么)。如果你跟我一样,请检查一下

2 个答案:

答案 0 :(得分:3)

你看不到任何东西,因为dataTaskWithRequest是异步的,而你的游乐场就在'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

答案 1 :(得分:0)

在我改变" 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)"}})