0

I get "fail 998" when i click the button as a first time. And then I get "success 999" when i click second time. It should be Asynchronous problem that's why i have added 'DispatchQueue' code line but it did not work. I should get "success 999" when i hit the button as a first time. How can i fix this problem? (By the way swift version is 4.1)

Here is the source code:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var lblDetail: UILabel!

var globalTempValue = ""

override func viewDidLoad() {
    super.viewDidLoad()
}


struct MyGitHub: Codable {
    let resultCode: String?
    private enum CodingKeys: String, CodingKey {
        case resultCode
    }
}

@IBAction func btnClickAction(_ sender: Any) {
  callMyApi()

    if (globalTempValue == "999")
    {
       print ("success 999")
    }
    else
    {
        print ("fail 998")
    }
}

func callMyApi()
{
    guard let gitUrl = URL(string: "https://transsupp.com/tApp/ws01.ashx") else
    { return }
    URLSession.shared.dataTask(with: gitUrl)
    {
            (data, response , error) in
            guard let data = data else { return }
            do
            {
                let decoder = JSONDecoder()
                let gitData = try decoder.decode(MyGitHub.self, from: data)
                DispatchQueue.main.async
                    {
                        self.globalTempValue = gitData.resultCode!
                    }
            }
            catch
                let err
            {
                print("Err", err)
            }
    }.resume()
}
}

web api returns this structure:

{
  "resultCode": "999",
  "resultMessage": "ok",
  "showPopUpPage": "True",
  "contentTextOfPopUpPage": "ws01Settings4Colors.ashx<br/>table:renkAyarlari<br/>showPopUpPage:True<br/><a href=https://www.google.com>click for the link brother</a>and this a skip line in here<br/>",
  "backgroundColor": "4D5656",
  "textColorOnThePage": "FFFFFF",
  "alertTextColorOnThePage": "E91E63",
  "buttonTextColor": "FFFFFF",
  "buttonBackgroundColor": "81D4FA",
  "alertButtonTextColor": "FFFFFF",
  "alertButtonBackgroundColor": "E91E63",
  "inputTextColor": "4D5656",
  "inputBackgroundColor": "FFFFFF",
  "dropDownMenuTextColor": "4D5656",
  "dropDownMenuBackgroundColor": "FFFFFF",
  "showBackgroundImage": "False",
  "backgroundImagePath": "http://transsupp.com/app/Assets/BackgroundImages/other_background.png"
}
1

2 Answers 2

1

Use completion block to perform action after async task.

func callMyApi(param: String, completion: @escaping (_ result : MyGitHub?, _ error: Error?) -> Void)
    {
        guard let gitUrl = URL(string: "https://transsupp.com/tApp/ws01.ashx") else
        { return }
        URLSession.shared.dataTask(with: gitUrl)
        {
            (data, response , error) in
            guard let data = data else { return }
            do
            {
                let decoder = JSONDecoder()
                let gitData = try decoder.decode(MyGitHub.self, from: data)
                DispatchQueue.main.async
                    {
                        completion(gitData, nil)
                }
            }
            catch
                let err
            {
                print("Err", err)
                completion(nil, err)
            }
            }.resume()
    }

Call the above function:

self.callMyApi(param: "PRARAM_STRING") { (result, error) in
        if result?.resultCode == "999"
        {
            print ("success 999")
        }else{
            print ("fail 998")
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for reply. But how can i send parameters when i call self.callMyApi function. What i am gonna write instead of 'result' and instead of 'error' when i am calling this function. Can you update your reply if it is possible? @Rocky
@mannyCalavera - check updated answer, just added single parameter as type String, you can add parameters as per your requirement. 'result' & 'error' are not parameter, these are returned values from completion block.
0

You call your API then without waiting for the response you check the globalTempValue which at that point is equal "". The second time you succeed because by that time the result has come back from your first call. You fix this in multiple ways, one of them being inside the dataTask closure, the other with property observer on globalTempValue like this:

var globalTempValue: String = "" {
    willSet{
        if (newValue == "999")
        {
            print ("success 999")
        }
        else
        {
            print ("fail 998")
        }
    }
}

2 Comments

Let me tell you what i did: I wrote your solution in 'btnClickAction' after callMyApi(). And then i hit the button but It does not work. I mean i don't see anything in output dialogBox in xcode after i hit the button. By the way of course i keep ' var globalTempValue = "" ' defination between line 'viewDidLoad' and the 'UIViewController' @Andras M.
My code doesn’t go in the btnClickAction but it replaces the globalTempValue declaration instead. This way you declare the variable and assign it an initial vslue of an empty string and add a property observer that is triggered when the property is about to change and it prints the newValue

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.