提问者:小点点

通过JSON-swift[duplication]解析数据后使用数据


我是一个初学Swift编码的人,正在尝试从NewsAPI网站解析JSON数据并使用它。 我已经成功地解析了JSON数据,并且它是通过结构来组织的,但是我无法将它设置为后台线程之外的变量,也无法在后台线程之外使用它。 有什么建议吗? 我已经包含了我的代码。

谢谢

import UIKit

class ViewController: UIViewController {

    var test:Int?

    override func viewDidLoad() {
        super.viewDidLoad()
        GrabJSON()


    }

    @IBOutlet weak var labelTime: UILabel!





    func GrabJSON() {

    // hit the API endpoint
         let urlString = "http://newsapi.org/v2/everything?q=bitcoin&from=2020-05-13&sortBy=publishedAt&apiKey=_________(it actually is here)"

         let url = URL(string: urlString)

         guard url != nil else {
             return

         }

         let session = URLSession.shared
         let dataTask = session.dataTask(with: url!) { (data, response, error) in

             // check for errors
             if error == nil && data != nil {
                 // if there is no error and there is data

                 let decoder = JSONDecoder()

                 do {


                 //parse json
             let newsFeed = try decoder.decode(NewsFeed.self, from: data!)

                    print(newsFeed)



             }
             catch {
                 print("error in JSON parsing")
             }

             }


         }

         // makes the API call

        dataTask.resume()

     }
}

共1个答案

匿名用户

由于session.dataTask()是异步的(您向它传递一个回调),因此您可以类似地在GrabJSON函数中提供一个回调参数,如下所示:

func GrabJSON(callback: NewsFeed -> Void) {

     // hit the API endpoint
     let urlString = "http://newsapi.org/v2/everything?q=bitcoin&from=2020-05-13&sortBy=publishedAt&apiKey=_________(it actually is here)"

     let url = URL(string: urlString)

     guard url != nil else {
         return
     }

     let session = URLSession.shared
     let dataTask = session.dataTask(with: url!) { (data, response, error) in

         // check for errors
         if error == nil && data != nil {
             // if there is no error and there is data

             let decoder = JSONDecoder()

      do {

             //parse json
             let newsFeed = try decoder.decode(NewsFeed.self, from: data!)

                print(newsFeed)
                callback(newsFeed) // call the callback
         }
         catch {
             print("error in JSON parsing")
         }
     }

     // makes the API call
    dataTask.resume()
 }

那么在其他地方,您可以像这样使用它:

GrabJson { newsFeed in 
   // do stuff with newsFeed json
}