ios - 使用 Swift 返回具有自定义数据类型的 JSON 数据时遇到问题

标签 ios json swift

<分区>

我在使用这段本质上下载 JSON 数据并对其进行解析以返回 returnInfo 的代码时遇到了问题。当我打印信息时,它是完整的,但是当它被返回时,结构默认值被返回。不确定我做错了什么任何帮助将不胜感激!

如果您需要任何其他信息,请告诉我,我很乐意提供。

import Foundation

struct stockData {
   var name: String = ""
   var askPrice: String = ""
   var percentageChange: String = ""
}

class stockinfo {

    init () {

    }

    func getInfo (stock: String) -> stockData{

            let stockSymbol = stock // Sets stock symbol
            var returnInfo = stockData()

            // Configuration for request and starts the connection

        let requestURL: NSURL = NSURL(string: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + stockSymbol + "%22)&env=store://datatables.org/alltableswithkeys&format=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("JSON File Downloaded Successfully")

                do{

                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

                    // Parses out the JSON Query into data to be assigned to a variable and returned

                    let query: NSDictionary = json["query"] as! NSDictionary
                    let results: NSDictionary = query["results"] as! NSDictionary
                    let quote: NSDictionary = results["quote"] as! NSDictionary
                    let companyName: String = quote["Name"] as! String
                    let askPrice: String = quote["Ask"] as! String
                    let percentageChange: String = quote["ChangeinPercent"] as! String

                    // Places JSON data into return struct
                    print(companyName)
                    print(askPrice)
                    print(percentageChange)

                    returnInfo.name = companyName
                    returnInfo.askPrice = askPrice
                    returnInfo.percentageChange = percentageChange

                } catch {
                    print("Error with Json: \(error)")
                }
            }
        }
        task.resume()
        return returnInfo
    }
}

最佳答案

您需要一个完成处理程序来等待 async 调用 dataTaskWithRequest 完成。像这样修改您的代码:

func getInfo (stock: String, completion: (cName: String, price: String, percentChange: String) -> ()) -> stockData{

//your code
let companyName: String = quote["Name"] as! String
                let askPrice: String = quote["Ask"] as! String
                let percentageChange: String = quote["ChangeinPercent"] as! String


                // Places JSON data into return struct
                print(companyName)
                print(askPrice)
                print(percentageChange)
             completion(cName: companyName, price: askPrice, percentChange: percentageChange)

}
//your code

然后每当你想调用它时,基本上是在按下按钮之后,或者如果你喜欢在 viewDidLoad 中调用它:

getInfo("your string") {(name, price, change) in
///use the three values how you want.
}

关于ios - 使用 Swift 返回具有自定义数据类型的 JSON 数据时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38130704/

上一篇:ios - 尝试使用 Swift3 将图像上传到 CloudKit 时出错

下一篇:ios - iOS 是否支持 WAV 文件?

相关文章:

ios - 在没有导航 Controller 的情况下强制在 UINavigationBar 中显示后退按钮

json - 如何在部署aws时在json文件中添加gitlab用户定义的变量?

objective-c - NSFullSizeContentViewWindowMask 和标题/工具栏高度?

ios - InterfaceBuilder 目标/操作中的 UIGestureRecognizer

ios - 完成按钮事件 MPMoviePlayerController

ios - FCM ios 配置

python - 将 JSON 或 XML 或 CSV 数据添加到 MySQL 服务器

ios - 在 TableView 中仅显示一次 json 数组中的重复元素 swift

ios - NSJSONSerialization.JSONObjectWithData 改变返回结果的内容?

ios - 在 Swift 中呈现 View Controller 时关于不可见标签栏的问题