0

Trying to poll the content of a website, no matter if JSON or REST API, I cannot seem to make it work. The same code works for iOS App, but will not get the content when being used within a Swift macOS Terminal application. What's the main reason?

The project does not have an Info.plist file.

Here's a code example that works within an iOS application, but not within the macOS Terminal application. I call the function with a simple jsonParser(), which initiates the NSURLSession and prints the JSON when it's arrived.

enum JSONError: String, ErrorType {
    case NoData = "ERROR: no data"
    case ConversionFailed = "ERROR: conversion from JSON failed"
}

func jsonParser() {
    let urlPath = "https://api.coindesk.com/v1/bpi/currentprice.json"
    guard let endpoint = NSURL(string: urlPath) else {
        print("Error creating endpoint")
        return
    }
    let request = NSMutableURLRequest(URL:endpoint)
    NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
        do {
            guard let data = data else {
                throw JSONError.NoData
            }
            guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary else {
            throw JSONError.ConversionFailed
        }
        print(json)
    } catch let error as JSONError {
        print(error.rawValue)
    } catch let error as NSError {
        print(error.debugDescription)
    }
    }.resume()
}
  • Can you make a [small, self-contained, compilable](http://www.sscce.org/) Swift file that reproduces the problem when you run it, and post it? – zneak Jun 20 '16 at 20:43
  • Duplicate of http://stackoverflow.com/questions/25126471/cfrunloop-in-swift-command-line-program ? – Martin R Jun 20 '16 at 21:18
  • Edited to provide example code. – Florian Uhlemann Jun 21 '16 at 05:12
  • 1
    @FlorianUhlemann This code comes directly from [my answer here](http://stackoverflow.com/questions/31805045/how-to-parse-json-in-swift-using-nsurlsession/31808605#31808605) and I don't see why you would not use Martin's solution. Just add `exit(0)` after `print(json)` when using `dispatch_main()` and you're done. – Eric Aya Jun 21 '16 at 07:12
  • Eric, This indeed seems to be the answer. Adding dispatch_main() at the end of the main application code fixes the problem. – Florian Uhlemann Jun 21 '16 at 15:21

1 Answers1

1

I was able to solve my problem by adding

dispatch_main()

at the end of my main program code. Listed above was the function to request the web data. Thanks to Martin and Eric for pointing it out.