heisenberg heisenberg - 10 months ago 47
Swift Question

Swift: Getting nil when trying to query api

I have troubles to get the stock price from the api. I'm using the SwiftyJSON framework to receive the data. It gives me nil in the console when I execute the code. I somehow can't find the bug.

@IBAction func buttonTapped(sender: AnyObject)

let markitOnDemandURL = "http://dev.markitondemand.com/MODApis/Api/v2/Quote/jsonp?symbol=AAPL&callback=myFunction"

func getJSON() {

let url = NSURL(string: markitOnDemandURL)
let request = NSURLRequest(URL: url!)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request) {(data, response, error) -> Void in

if error == nil {

let swiftyJSON = JSON(data: data!)
let theTitle = swiftyJSON["LastPrice"].string



Here is the api that I'm using: http://dev.markitondemand.com/MODApis/Api/v2/Quote/jsonp?symbol=AAPL&callback=myFunction

It would be great if you could have a look at my code and help me to fix this issue. Thanks for your efforts.

Answer Source

The result currently your are getting from this api is

myFunction({"Status":"SUCCESS","Name":"Apple Inc","Symbol":"AAPL","LastPrice":116.05,"Change":1.98999999999999,"ChangePercent":1.74469577415395,"Timestamp":"Mon Oct 10 00:00:00 UTC-04:00 2016","MSDate":42653,"MarketCap":625328810150,"Volume":36235956,"ChangeYTD":105.26,"ChangePercentYTD":10.2508075242257,"High":116.75,"Low":114.72,"Open":115.02})

which is an INVALID JSON

Removing myFunction( from the beginning and ) at the end will make it a valid json


  "Status": "SUCCESS",
  "Name": "Apple Inc",
  "Symbol": "AAPL",
  "LastPrice": 116.05,
  "Change": 1.98999999999999,
  "ChangePercent": 1.74469577415395,
  "Timestamp": "Mon Oct 10 00:00:00 UTC-04:00 2016",
  "MSDate": 42653,
  "MarketCap": 625328810150,
  "Volume": 36235956,
  "ChangeYTD": 105.26,
  "ChangePercentYTD": 10.2508075242257,
  "High": 116.75,
  "Low": 114.72,
  "Open": 115.02

You can use various tools like POSTMAN or links like http://jsonviewer.stack.hu/ and http://jsonlint.com/ to validate your JSON.