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/)
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.
This is my screenshot of the playground:
+
CFRunLoop in Swift Command Line Program
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). 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()`. The asynchronous task does not get the change to run.
You can call this in the end, after task.resume
:
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
also 'import XCPlayground', something like this:
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
EDIT:
In Swift 3, this changed a bit.
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With