[英]Class variable assignment is not working inside a Alamofire request block
I am trying to assign a Alamofire
request result to a TableView
class variable. 我正在尝试将Alamofire
请求结果分配给TableView
类变量。
I have realized that when I use the self.notifications variable within Alamofire
request block, it works. 我已经意识到,当我在Alamofire
请求块中使用self.notifications变量时,它可以工作。 But when I call self.notifications outside of Alamofire
it is nil and self.notifications is not be assigned by reference. 但是,当我打电话之外self.notifications Alamofire
它是零,self.notifications并非依据进行分配。 It seems like a copy variable 好像是一个复制变量
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)
I expect self.notifications to not be nil after Alamofire
request 我希望Alamofire
请求后Alamofire
不会为零
The code in alamofire response will be executed when some response is received from the URL. 当从URL接收到某些响应时,将执行alamofire响应中的代码。 Here the execution pointer is not going to wait for that response as it is a asynchronous call back and will continue to execute the next statement. 在这里,执行指针将不等待该响应,因为它是异步回调,并且将继续执行下一条语句。 So It will execute the statement outside the Alamofire first and as it is not initialised with any value, it will be nil and after some response is received some value is assigned to the class variable. 因此,它将首先在Alamofire外部执行该语句,并且由于未使用任何值对其进行初始化,因此它将为nil,并且在收到某些响应之后,会将一些值分配给类变量。
Below link will be able to get you through the async code 下面的链接将使您了解异步代码
https://medium.com/ios-os-x-development/managing-async-code-in-swift-d7be44cae89f https://medium.com/ios-os-x-development/managing-async-code-in-swift-d7be44cae89f
最后,问题是使用Alamofire同步从此解决了回购 ,甚至与一个更干净的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.