I've just started 'Alamofire' for JSON parsing. Now I'm facing some problem which are as follow:
Problem Statement : Unable to access data outside the Alamofire block.
Coding Stuff :
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 block is an asynchronous callback. In other words, it will run the completion block whenever the response is ready. If you would like to use the dataValue
whenever it is set. You can take advantage of didSet
in variable properties.
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 uses block for getting web API's So as according to your problem . You can check by putting break points into block and after block.
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.
}
}
That line doesn't print anything because it will debug first, while your alamofire block debugs and returns when you get response & it will print value.
So I think you can use value of dataValue into another functions as it stores after getting response into block.
Hope this will help you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.