gpt4 book ai didi

ios - 类变量分配在 Alamofire 请求 block 内不起作用

转载 作者:行者123 更新时间:2023-11-28 11:33:43 27 4
gpt4 key购买 nike

我正在尝试将 Alamofire 请求结果分配给 TableView 类变量。

我已经意识到,当我在 Alamofire 请求 block 中使用 self.notifications 变量时,它会起作用。但是当我在 Alamofire 之外调用 self.notifications 时,它是 nil 并且 self.notifications 不是通过引用分配的。好像是复制变量

class NotificationsTableView: UITableViewController{

var notifications: Notification!
let uri = Helper.URLDEV + "/api_x/notifications/"
override func viewDidLoad() {
super.viewDidLoad()

tableView.cellLayoutMarginsFollowReadableWidth = true
self.tableView.delegate = self
self.tableView.dataSource = self
print("Table loaded")
let auth_code = ["Authorization": "Token " + Helper.getMyToken() ]
Alamofire.request(self.uri, parameters: nil, encoding: URLEncoding.default, headers: auth_code).responseJSON { response in
guard let data = response.data else { return }
do {
let decoder = JSONDecoder()
//This is working properly
self.notifications = try decoder.decode(Notification.self, from: data)
print(self.notifications?.results?[2].notificationData?.body ?? 999)

} catch let error {
print(error)
}
}
print("URI: \(uri)")
//Here is just nil, if I didn't assign a value before
print(self.notifications == nil)

我希望 self.notifications 在 Alamofire 请求后不为 nil

最佳答案

当从 URL 收到一些响应时,将执行 alamofire 响应中的代码。这里执行指针不会等待该响应,因为它是一个异步回调,并将继续执行下一条语句。因此它将首先执行 Alamofire 外部的语句,并且由于它没有用任何值初始化,它将为 nil,并且在收到一些响应后,一些值被分配给类变量。

下面的链接将能够让你通过异步代码

https://medium.com/ios-os-x-development/managing-async-code-in-swift-d7be44cae89f

关于ios - 类变量分配在 Alamofire 请求 block 内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56173464/

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