gpt4 book ai didi

ios - 将对象从 URLSession 传递到 ViewController

转载 作者:搜寻专家 更新时间:2023-11-01 07:11:17 24 4
gpt4 key购买 nike

我正在尝试将我创建的名为 detail 的对象从名为 RestManager.swift 的 swift 文件传递​​到 ViewController。该对象包含所有元素,但是当我在我的 View Controller 中调用它时,它是空的。从我在网上收集到的信息来看,它可能与在后台线程上工作的 URLSession 有关

我的 RestManager.swift 看起来像这样。

class RestManager {


func reqDetails(id: Int) {
// Create URL
let id = String(id)
let url = "https://website.example.com/"
let url = URL(string: url + id)!

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

if error != nil
{
print ("ERROR")
}

else
{
if let content = data
{

let jsonData = JSON(data: content)

let id = jsonData["id"].intValue
let name = jsonData["title"]["rendered"].string!
let link = jsonData["link"].url!
let content = jsonData["content"]["rendered"].string!


// Create Object
let detail = Detail(id: id, name: name, content: content, thumbnailUrl: link)
self.details.append(detail)

}
}
}
task.resume()
}
}

我的 View Controller 看起来像这样:

class DetailViewController: UIViewController {

var ListingID = Int()
let restManager = RestManager()

@IBOutlet weak var ContentLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
restManager.reqDetails(id: ListingID)
ContentLabel.text? = restManager.details[0].name // After running the app this index value is out of range.


}

..

}

最佳答案

像这样在函数中使用closer来传递数据

'

func reqDetails(id: Int,completionHandler:@escaping (_ detilObject:Detail)->Void) {
// Create URL
let id = String(id)
let url = "https://website.example.com/"
let url = URL(string: url + id)!

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

if error != nil
{
print ("ERROR")
}

else
{
if let content = data
{

let jsonData = JSON(data: content)

let id = jsonData["id"].intValue
let name = jsonData["title"]["rendered"].string!
let link = jsonData["link"].url!
let content = jsonData["content"]["rendered"].string!


// Create Object
let detail = Detail(id: id, name: name, content: content, thumbnailUrl: link)
self.details.append(detail)
completionHandler(self.details)

}
}
}
task.resume()
}

'

然后像这样调用你的函数。'

restManager.reqDetails(id: ListingID , completionHandler: { (detail) in
// here is your detail object
})

'

关于ios - 将对象从 URLSession 传递到 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44741399/

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