6

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

0

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

1 Comment

Wow I must have asked sooner... :) Definitely works. Thank you so much!
0

works fine in my project after I changed "http" -> https, Apple announced “App Transport Security” for iOS 9 and OSX 10.11 El Capitan

    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:

 <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

    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)"}})

Comments

-1

Swift 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()
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.