ios - 类变量分配在 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 在请求后不会为零
解决方案
当从 URL 接收到一些响应时,将执行 alamofire 响应中的代码。在这里,执行指针不会等待该响应,因为它是异步回调,并将继续执行下一条语句。所以它将首先在 Alamofire 之外执行该语句,并且由于它没有用任何值初始化,它将为 nil,并且在收到一些响应后,一些值被分配给类变量。
下面的链接将能够让您通过异步代码
https://medium.com/ios-os-x-development/managing-async-code-in-swift-d7be44cae89f
推荐阅读
- c - Android NDK 中用于解码 mp3 的函数 hip_decode1_headers 返回 0
- ios - 在具有另一个视图的 UIView 上启用拖动
- python - 如何使用 Python 将应用程序上传到 Google Play
- laravel - 如何解决 laravel 中的类缺失问题?
- ios - SSO 功能逻辑在科尔多瓦 IOS 应用程序中不起作用
- c - 如何从图片 GTK 3 中选择像素颜色
- r - 如何使用 igraph 计算道路网络上城市的介数
- windows - Install4j 更新安装 context.isUpdateInstallation 总是返回 false
- java - 使用 reactor-grpc 去抖动类似的请求
- php - 使用关系选择时如何从 Laravel 的主表中选择特定字段