[英]How to access data outside the Alamofire block using swift 3.0
我剛剛開始“ Alamofire”進行JSON解析。 現在,我面臨一些問題,如下所示:
問題陳述:無法訪問Alamofire塊外部的數據。
編碼資料:
import UIKit
import Alamofire
class ViewController: UIViewController
{
var dataValue = String()
override func viewDidLoad()
{
super.viewDidLoad()
Alamofire.request("url") .responseJSON
{ response in
dataValue = response.result.value
print(dataValue) // It prints value
}
print(dataValue) //It does not print any thing or nil.
}
}
Alamofire塊是一個異步回調。 換句話說,只要響應准備就緒,它將運行完成塊。 如果您想在設置dataValue
時使用它。 您可以在變量屬性中利用didSet
優勢。
class ViewController: UIViewController
{
var dataValue = String() {
didSet {
// do something here
print(dataValue) // It prints value
}
}
override func viewDidLoad()
{
super.viewDidLoad()
Alamofire.request("url") .responseJSON
{ response in
dataValue = response.result.value
print(dataValue) // It prints value
}
print(dataValue) //It does not print any thing or nil.
}
}
var dataValue = String()
override func viewDidLoad()
{
super.viewDidLoad()
Alamofire.request("url") .responseJSON
{ response in
dataValue = response.result.value
self.myFunction(str: dataValue)
}
}
func myFunction(str: String)
{
print("str value ====%@",str)
}
Alamofire根據您的問題使用代碼塊獲取Web API。 您可以通過將斷點放在塊中和塊之后來進行檢查。
class ViewController: UIViewController
{
var dataValue = String()
override func viewDidLoad()
{
super.viewDidLoad()
Alamofire.request("url") .responseJSON
{ response in
dataValue = response.result.value
print(dataValue) // It prints value
}
print(dataValue) //It does not print any thing or nil.
}
}
該行不會打印任何內容,因為它將首先進行調試,而您的alamofire塊將在得到響應時進行調試並返回,並且將打印值。
因此,我認為您可以將dataValue的值用於在將響應放入塊后存儲的其他函數中。
希望這會幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.