gpt4 book ai didi

Swift:尝试查询 api 时获取 nil

转载 作者:行者123 更新时间:2023-11-30 12:59:44 25 4
gpt4 key购买 nike

我无法从 api 获取股票价格。我正在使用 SwiftyJSON 框架来接收数据。当我执行代码时,它在控制台中给我 nil 。我不知怎的找不到这个错误。

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

如果您能查看我的代码并帮助我解决此问题,那就太好了。感谢您的努力。

最佳答案

当前您从该 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})

这是一个无效的 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。

关于Swift:尝试查询 api 时获取 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39983884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com