我很难从api获得股票价格。我使用SwiftyJSON框架来接收数据。当我执行代码时,它在控制台中给出了nil。我不知道怎么找不到这个bug。
import UIKit
class ViewController: UIViewController
{
@IBOutlet weak var inputQuote: UITextField!
@IBAction func buttonTapped(sender: AnyObject)
{
var stockQuote = inputQuote.text
getJSON(stockQuote!)
}
override func viewDidLoad()
{
super.viewDidLoad()
}
func getJSON(quote: String)
{
let markitOnDemandURL = "http://dev.markitondemand.com/MODApis/Api/v2/Quote/jsonp?symbol=" + quote.uppercaseString + "&callback=myFunction"
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 stockPrice = swiftyJSON["LastPrice"].stringValue
print(stockPrice)
}
else
{
print("error")
}
}
task.resume()
}
}
以下是我使用的API:http://dev.markitondemand.com/MODApis/Api/v2/Quote/jsonp?symbol=AAPL&callback=myFunction
如果您可以查看我的代码并帮助我解决此问题,那就太棒了。谢谢你的努力。
答案 0 :(得分:0)
目前你从这个api得到的结果是
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})
INVALID JSON
在结尾处删除 myFunction(从头开始)将使其成为有效的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
}
您可以使用POSTMAN等各种工具或http://jsonviewer.stack.hu/和http://jsonlint.com/等链接来验证您的JSON。