【发布时间】:2019-05-16 17:08:41
【问题描述】:
我正在尝试将 Alamofire 请求结果分配给 TableView 类变量。
我意识到当我在Alamofire 请求块中使用 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 请求之后不会为零
【问题讨论】:
-
这是任何异步调用背后的逻辑,你需要从 Alamofire 回调开始旅程