0

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.

ksm18
  • 93
  • 8
  • Can't you trigger `if(Global.variable){doThis()}` inside an aysnc method, to be called when the setFlag API call finishes? – Mark Aug 06 '15 at 14:53
  • 1
    You haven't provided enough information. iOS apps are single-threaded unless you explicitly use multithreading or a library that does. Are you running some sort of async method that has a completion block? Are you using dispatch_async and passing in a background queue? You need to provide a more complete description of the situation before we can help you. – Duncan C Aug 06 '15 at 15:00
  • Look into NSOperation (more specifically NSBlockOperation), NSOperationQueue, and Dependencies. You can wait until the execution of your API call has finished to execute your if statement if there is no completion handler for your API call. Apple has a great WWDC video on this. – Ian Aug 06 '15 at 15:20
  • 2
    Provide more details about how setFlag is implemented. Why is it an asynchonrous function if all its doing is setting a flag (ok, I know its pseudo code, but it must be doing something else for it to be asynchronous). If it *has to be* asynchronous, then change it to accept a block as a parameter, when it completes the bock would get called. Within the block is where you call doThis(). – Gruntcakes Aug 06 '15 at 15:54
  • I added the actual code--maybe this will help. @Mark, that did not work either. – ksm18 Aug 06 '15 at 18:25

1 Answers1

0

In this line:

if(Global.loggedIn){ // do whatever--won't happen

Take whatever you want to have happen and put it in a function:

func doWhatever() {
    // do whatever
}

Then, in the completion handler closure for your NSURLConnection, change this section of your code by adding one line:

...
if (tempString == "loggedin"){
    Global.loggedIn = true
    doWhatever()            // <--- Add this line
}
...

Give it a try. Let us know if it works. :)

Aaron Rasmussen
  • 13,082
  • 3
  • 42
  • 43