2

I'm very new on stackoverflow & very very new with Swift. I need to get result from PHP, using Swift code like the following :

func GetEtatO2()
{
    let url = NSURL(string: "http://www.exxagon.com/php/GetEtatO2.php")
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!,
        completionHandler:
        {
            (data, response, error) -> Void in
            if error != nil
            {
                print("Error: \(error)")
                return
            }
            else
            {
                print("data ==> \(data)")
                print("response ==> \(response)")
                print("error ==> \(error)")
                let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
                print("responseString ==> \(responseString!)")
                self.EtatO2 = responseString!
            }
        }
    )
    task.resume()
}

The string returned by my PHP code is "ON" ou "OFF".

I can get this string the else part of my code, but, the line self.EtatO2 = responseString! seems to do nothing; I mean the value "ON" ou "OFF" is not stored in var EtatO2.

I'm sure I miss something bigger than me ... can you give some help ? Many thanks is advance.

2 Answers 2

1

I finally found a solution : inserting

 dispatch_async(dispatch_get_main_queue(), { () -> Void in  ...
as follow
`@IBAction func GetEtatO2(sender: UIButton) {
    let Url = NSURL(string: "http://www.exxagon.com/php/GetEtatO2.php")
    let task = NSURLSession.sharedSession().dataTaskWithURL(Url!, completionHandler: { (data, response, error) -> Void in
            print( ">>>> Debut >>>>")
            print("Error: \(error)")
            if error != nil
            {
                return
            }
            else
            {
                print("data: \(data)")
                print("Response: \(response)")
                let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
                print("responseString: \(responseString)")
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.EtatO2Label.text = responseString
                })
            }
            print( "<<<< Fin <<<<")
    })
    task.resume()
  }

By this way, pressing GetEtatO2 button, display the right status in a Label.

Sign up to request clarification or add additional context in comments.

Comments

0

Make sure you're not trying to use self.Etat02 until after the completion handler is called. One way to do this is to add a completion handler to GetEtat02().

func GetEtatO2(completion:(String) -> ())
{
    let url = NSURL(string: "http://www.exxagon.com/php/GetEtatO2.php")
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!,
        completionHandler:
        {
            (data, response, error) -> Void in
            if error != nil
            {
                completion("Error: \(error)")
            }
            else
            {
                let responseString = String(data: data!, encoding: NSUTF8StringEncoding)

                completion(responseString!)
            }
        }
    )
    task.resume()
}

Then you are able to call GetEtat02() and use the response like this:

GetEtatO2() { responseString in
    // This won't run until the NSURLSession completes
    print(responseString)
}

// responseString doesn't exist here, only in the closure above

5 Comments

Sure, but in the code I shared before, where should I place it ?
I've added an example for you. Since the NSURLSession runs asynchronously, any code outside of the closure will be executed before the completion handler is called and self.Etat02 won't yet be available.
I'll try it in outside playground surely tomorrow, and let know the result
If you run asynchronous code in the playground make sure you import XCPlayground and call XCPSetExecutionShouldContinueIndefinitely()
I tried outside playground but it does not work. The result of p.GetEtatO2() { response in print(response) } is ()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.