Duck.P Duck.P - 1 year ago 125
Swift Question

how to use server response and data in other functions in swift 3

am making a post request to a server and the server responds with some data,am storing the recived data in a variable named json now am trying to access this variable from other functions but i get an error : "use of unresolved identifier "json"

here is the code incase u need it

@IBAction func Login(_ sender: UIButton) {
guard let url = URL(string: "url was here..lol") else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
let postString = "data to be posted"
print(postString)
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try? JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
let token = json?["access_token"] as! String
print (json)

}
}
}
task.resume()

}

Answer Source

You need to declare the variables you want to share between functions on the class level so they can be accessed by each function in the class. token is an instance property of the class with this implementation, so each class instance has its own variable called token that can be accessed anywhere inside the class.

class MyViewController: UIViewController {
    var token = ""

    @IBAction func Login(_ sender: UIButton) {
        guard let url = URL(string: "url was here..lol") else {return}
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        let postString = "data to be posted"
        print(postString)
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let response = response {
                print(response)
            }
            if let data = data {
                guard let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {return}
                guard let receivedToken = json["access_token"] as? String else {return}
                self.token = receivedToken
                otherFunction()
            }
        }
    task.resume()
    }

    func otherFunction(){
        print(token)
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download