Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting data from URL in Swift

Tags:

json

ios

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/)

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:

enter image description here

+

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

like image 766
Joy Avatar asked Sep 25 '22 08:09

Joy


1 Answers

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
like image 173
Laura Calinoiu Avatar answered Oct 10 '22 17:10

Laura Calinoiu