From a programming standpoint, because of the way the code is written I can't necessarily work around this.
Basically, in pseudocode:
if NSUserDefaults' stored token exists{
setFlag(token)
// setFlag will make an API call with the token and either set Global.variable to true or leave it at false
if(Global.variable){doThis()}
}
Basically, the condition check happens before the setFlag finishes, so it will never be true at the time of checking. Even if I add a second global boolean along the lines of didSetFlagFinishExecuting, I get the same issue--conditional happens before the others. I put it in a while loop but it was stuck in an infinite loop because of the way I have coded things. I don't have experience with thread locks/ GCD. I prefer not to use it, but I will if I have to. Any suggestions?
EDIT: Actual code
// in viewDidLoad
let defaults = NSUserDefaults.standardUserDefaults()
if let stringOne = defaults.valueForKey("sessionKey") as? String{
getStatus(stringOne)
if(Global.loggedIn){ // do whatever--won't happen
// as an extension to ViewController
func getStatus(sessionKey: String){
let url : String = "http://whatever" + sessionKey
let request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"
var queue : NSOperationQueue = NSOperationQueue()
var returnString : String = ""
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{(response:NSURLResponse!, responseData:NSData!, error: NSError!) -> Void in
if error != nil
{
println(error.description)
returnString = error.description
}
else
{
var errors: NSError?
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData!, options: NSJSONReadingOptions.MutableContainers, error: &errors) as! NSDictionary
var tempString = jsonData["last_status"] as! String!
print(tempString)
if (tempString == "loggedin"){
Global.loggedIn = true
}
Global.finished = true
print("hello")
}
}
})
}
So if I print Global.loggedIn at the end here, it will be true. It's just none of this finishes in time. Even if I make it a return function, for whatever reason the condition in viewDidLoad will read it as false, THEN "hello" will be printed.
In this line:
Take whatever you want to have happen and put it in a function:
Then, in the completion handler closure for your
NSURLConnection
, change this section of your code by adding one line:Give it a try. Let us know if it works. :)