首页 > 解决方案 > 类变量分配在 Alamofire 请求块中不起作用

问题描述

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

我已经意识到,当我在Alamofire请求块中使用 self.notifications 变量时,它可以工作。但是当我在它之外调用 self.notifications 时,Alamofire它是 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)

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

标签: iosswiftalamofire

解决方案


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

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

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


推荐阅读