在swift中解析json数据

t3psigkw  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(331)

我正在尝试创建一个ios应用程序,从网站读取mysql数据并将其显示给用户。以下是解析数据的文件:

import UIKit
protocol HomeModelDelegate{
func itemsDownloaded(bar_data:[DataModel])
}

class HomeModel: NSObject {
var delegate:HomeModelDelegate?
func getItems() {
    //Hit the web service Url
    let serviceUrl = "OMITTED"
    //Download the json data
    let url = URL(string: serviceUrl)
    if let url = url{
        //Create a URL Session
        let session = URLSession(configuration: .default)
        let task = session.dataTask(with: url, completionHandler: {(data, response, error) in
            if error == nil {
                //Succeeded                 
                //Call the parse json function on the data
                self.parseJson(data!)
            }              
            else {
                //Error occured
            }                             
        })          
       // Start the task
        task.resume()
    }             
    //Notify the view controller and pass the data back
}
 //Parse it out into DataModel structs
func parseJson(_ data:Data){        
    var bardataarray = [DataModel]()        
        //parse the data into DataModel structs
    do{
   //parse the data into a json object
        let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as! [Any]
    //loop through each result in the json array
        for jsonResult in jsonArray {
            //Cast json result as a dictionary
            let jsonDict = jsonResult as! [String:String]
            //create new bar data and set its properties
            let bardata = DataModel(name: jsonDict["Bar Name"]!, cover: jsonDict["Bar Cover"]!, deals: jsonDict["Drink Deals"]!)
        //add it to the array
            bardataarray.append(bardata)           
        }
        //TODO Pass the location array back to delegate 
        delegate?.itemsDownloaded(bar_data: bardataarray)         
    }
    catch{
        print("There was an error")
    }         
}
                         //eof
}

以下是数据模型文件:

import Foundation

struct DataModel {    
var name = ""
var cover = ""
var deals = ""
}

以下是视图控制器:

import UIKit
class ViewController: UIViewController, 
HomeModelDelegate, UITextViewDelegate {  
var bar_info = [DataModel]()   
var homeModel = HomeModel()

@IBOutlet weak var LionCoverView: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    homeModel.getItems()
    homeModel.delegate = self
    updateCover()
}

func updateCover(){
    let size = bar_info.count
    print(size)  
}

func itemsDownloaded(bar_data: [DataModel]) {
    //adding files to array that we can work with

    self.bar_info = bar_data

    print(bar_data[2].name)
}

}

在视图控制器中,我尝试将datamodels数组分配给我在函数itemsdownload中的视图控制器开头初始化的数组bar\u info,但是没有发送值。有人知道我做错了什么吗?我在itemsdownload中放置了一个print语句到控制台,以确保baru数据中的值存在,并且当我运行它时,程序正在从网站生成正确的值,那么为什么这些变量没有被分配到视图控制器开头的datamodel数组呢?

inb24sb2

inb24sb21#

您可以使用dispatchqueue.main.asynch来处理ui更新,如下所示,将对委托的调用移出 parseJson 功能

let task = session.dataTask(with: url, completionHandler: {(data, response, error) in
    if error == nil {
        self.parseJson(data!)
        DispatchQueue.main.async {
            delegate?.itemsDownloaded(bar_data: bardataarray)     
        }
    }
}

相关问题