[英]getting data from URL in Swift
I'm trying to download JSON file from server & following an tutorial to do this ( http://www.learnswiftonline.com/mini-tutorials/how-to-download-and-read-json/ )我正在尝试从服务器下载 JSON 文件并按照教程执行此操作( http://www.learnswiftonline.com/mini-tutorials/how-to-download-and-read-json/ )
First I tried 'checking the response' part (I added some part to see what's wrong)首先,我尝试了“检查响应”部分(我添加了一些部分以查看问题所在)
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()
This should print either "Everyone is fine~" or "Failed" but neither comes up... I tried to see statusCode so I put print(statusCode)
inside task
but again nothing is printed.这应该打印“每个人都很好〜”或“失败”,但都没有出现......我试图查看 statusCode 所以我将print(statusCode)
放在task
中,但再次没有打印任何内容。
This is my screenshot of the playground:这是我的操场截图:
+ +
CFRunLoop in Swift Command Line Program Swift 命令行程序中的 CFRunLoop
This was the answer I was looking for, since I was dealing with OS X command line application (I moved the whole bunch to playground to see what would happen).这是我一直在寻找的答案,因为我正在处理 OS X 命令行应用程序(我将整个团队搬到了操场上,看看会发生什么)。 Check this if you're the same with me如果你和我一样,请检查这个
You can not see anything because dataTaskWithRequest
is asynchronous, and your playground just stops after 'task.resume()`.您看不到任何东西,因为dataTaskWithRequest
是异步的,并且您的 Playground 只是在“task.resume()”之后停止。 The asynchronous task does not get the change to run.异步任务不会让更改运行。
You can call this in the end, after task.resume
:最后,您可以在task.resume
之后调用它:
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
also 'import XCPlayground', something like this:还有'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
This post may clarify more: How do I run Asynchronous callbacks in Playground这篇文章可能会澄清更多: 如何在 Playground 中运行异步回调
EDIT:编辑:
In Swift 3, this changed a bit.在 Swift 3 中,这发生了一些变化。
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
works fine in my project after I changed "http" -> https, Apple announced “App Transport Security” for iOS 9 and OSX 10.11 El Capitan在我更改“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()
the http response: 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";
} } } }
or error if use http或者如果使用 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)"}})
Swift 5斯威夫特 5
let requestURL: NSURL = NSURL(string: "https://irdirect.net/template_files/1294/stock-price.html")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("Everyone is fine, file downloaded successfully.")
do{
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any]
}
catch{ print("erroMsg") }
} else {
print("Failed")
}
}
task.resume()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.