Search code examples
swiftscopeswift2nsjsonserializationdo-catch

scope of do-catch in swift - cannot assign value to outside variable


I have made some code to make POST request to my php script which is placed on my servers. I have tested and that part is working fine. I got the problem with the returning result from the server - I get it in JSON format, and print in inside do-catch statement - its OK. I assign the returning variable to variable which is declared outside of the do-catch and its not "visible". Let me show my code, it will be more simplier to explain when you see the code:

//sending inputs to server and receiving info from server
    let json:[String:AnyObject] = [ "username" : username!, "password" : password!, "iphone" : "1" ]
    var link = "http://www.pnc.hr/rfid/login.php"
    var novi:String = ""

        do {
            let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)

            // create post request
            let url = NSURL(string: link)!
            let request = NSMutableURLRequest(URL: url)
            request.HTTPMethod = "POST"

            // insert json data to the request
            request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
            request.HTTPBody = jsonData

            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")


            let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
                if error != nil{
                    print("Error 55 -> \(error)")
                    return
                }

                do {
                    let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
                    print("FIRST PRINT -> \(result!["password"])")
                    novi = String(result!["password"])
                    //return result
                } catch {
                    print("Error  43-> \(error)")
                }
            }
            task.resume()
        }
        catch {
            //handle error. Probably return or mark function as throws
            print(error)

        }

    print("SECOND PRINT -> \(novi)")

If you see print("FIRST PRINT -> \(result!["password"])") - it executes normally and output all the variables. Then if you see print("SECOND PRINT -> \(novi)") at the end of the code it outputs empty sting - like I haven't assigned variable to it.


Solution

  • You are using an asynchronous block. The print statement will get run before your block has a chance to set novi.

    This issue is not a problem with do-catch it is a asynchronous issue.