gpt4 book ai didi

ios - 变量在 URLSESSION 中不可用

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

我正在 mvvm 方法中执行操作。我的代码如下。

食物模型:-

class foodModel: NSObject {



var name :String!
var city :String!
var imageurl :String!

init?(dictionary :JSONDictionary) {

guard let name = dictionary["name"] as? String,
let imageurl = dictionary["imageurl"] as? String,
let city = dictionary["city"] as? String else {
return
}

self.name = name
self.city = city
self.imageurl = imageurl

}
}

foodDataSourceModel:-

class foodDataSourceModel: NSObject {


var dataListArray:Array<foodModel>? = []


init(array :Array<[String:Any]>?) {
super.init()
var newArray:Array<[String:Any]> = []
if array == nil{

newArray = self.getJsonDataStored1()
}
else{
newArray = array!

}

var datalist:Array<foodModel> = []
for dict in newArray{

let model = foodModel(dictionary: dict)

datalist.append(model!)
}
self.dataListArray = datalist
}



}

typealias dummyDataSource1 = foodDataSourceModel
extension dummyDataSource1{

func getJsonDataStored1() ->Array<Dictionary<String,String>>{

let jsonArray = [["name":"Anjapar","imageurl":"","city":"india"],["name":"Anjapar","imageurl":"","city":"india"]] as Array<Dictionary<String,String>>

return jsonArray
}




}

foodViewModel:-

class foodViewModel: NSObject {






var datasourceModel:foodDataSourceModel

init(withdatasource newDatasourceModel:foodDataSourceModel) {
datasourceModel = newDatasourceModel
}


func datafordisplay(atindex index: Int) -> foodModel {
return datasourceModel.dataListArray![index]

}


func numberOfItemsInSection(section:Int) -> Int {

return (datasourceModel.dataListArray?.count)!
}


func loadData(){


loadFromWebserviceData { (newDataSourceModel) in

self.datasourceModel = newDataSourceModel!
}
}

func loadFromWebserviceData(completion :@escaping (foodDataSourceModel?) -> ()){


let url = URL(string :"http://example.com")!

URLSession.shared.dataTask(with: url) { data, _, _ in

if let data = data {

let json = try! JSONSerialization.jsonObject(with: data, options: [])
//let dictionaries = json as! [JSONDictionary]

let array = json as! Array<[String:Any]>
let newDataSource:foodDataSourceModel = foodDataSourceModel(array: array)
// DispatchQueue.main.async {
//
// }
completion(newDataSource)
}

}.resume()

}

}

foodViewController:-

@IBOutlet private weak var tableView: UITableView!


private var foodViewModel :foodViewModel!

init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, withViewModel viewModel:foodViewModel) {

super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

foodViewModel = viewModel
}


required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}



override func viewDidLoad() {
super.viewDidLoad()

// tableView.register(UINib(nibName: "foodCell", bundle: nil), forCellReuseIdentifier: "cell")

foodViewModel.loadData()

self.tableView .reloadData()

// Do any additional setup after loading the view.
}

// func numberOfSections(in tableView: UITableView) -> Int {
// return restaurtantViewModel.numberOfItemsInSection(section: Int)
// }



func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell")! as! foodCell


//cell.setRestaurtantData(restaurtant: foodModel)
cell.textLabel?.text = "rtyuiop"
//

return cell
}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


/*

}
*/

}

食物细胞:-

class foodCell: UITableViewCell {

@IBOutlet weak var name: UILabel!
@IBOutlet weak var city: UILabel!


override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}

func setRestaurtantData(restaurtant:foodModel)
{
self.name.text = restaurtant.name
self.city.text = restaurtant.city

}


override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)

// Configure the view for the selected state
}

}

这里没有输出。我需要在 TableView 中显示值。显示错误,无法从数据源获取单元格

{
"query": "sandwich",
"results_count": 12,
"page": 1,
"results": [
{
"name": "Caffè Macs",
"coordinates": {
"lat": 37.330576,
"lng": -122.029739
},
"meals": ["breakfast", "lunch", "dinner"]
},
...
]
}

这是模式,因此我需要获取“name”、“lng”和“lat”等值。从 Json 加载数据时出现一些问题。在 urlsession 任务中 - 显示为变量不可用。请检查。如何解决这个问题?

最佳答案

请更新您的viewDidLoad()。您必须设置tableview的委托(delegate)和数据源。

类里面的第一组:-

class yourClass: UIViewController,UITableViewDelegate , UITableViewDataSource

现在

override func viewDidLoad() {
super.viewDidLoad()

// tableView.register(UINib(nibName: "foodCell", bundle: nil), forCellReuseIdentifier: "cell")

foodViewModel.loadData()
self.tableView .delegate = self
self.tableview.dataSource = self
self.tableView .reloadData()

关于ios - 变量在 URLSESSION 中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49586028/

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