0
 var session_check = false
        if let value = makecookie.desc["Cookie"]{
            request.addValue(value, forHTTPHeaderField: "Cookie")
        }

        do{
        let response  = try String(contentsOf: url!, encoding: String.Encoding.utf8)
            NSLog(" response \(response)")
        }catch{
            NSLog("error")
        }


        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            DispatchQueue.main.sync(){

            if let e = error {
                NSLog("An error has occurred : \(e.localizedDescription)")
                return
            }
            print("Response Data=\(String(data: data!, encoding: .utf8)!)")

                do {
                    let object = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
                    guard let jsonObject = object else { return }

                    let result = jsonObject["session_valid_yn"] as? String
                    NSLog("object : \(object!)")

                    if result == "Y" {

                        session_check = true
                        return

                    }
                } catch let e as NSError {
                    print ("An error has occurred while parsing JSONObject : \(e.localizedDescription)")
                }
            }
        }

    task.resume()

    return session_check;

Put a cookie value when calling api

Cookies are required.

It then stores the value in session_check based on the result of the requested URL.

I want to process the page based on the value.

However, session_check is returned before the dataTask is executed asynchronously and the results are retrieved.

How do you handle this?

Is there a way to get the values ​​synchronously?

Dongle
  • 3
  • 1

1 Answers1

0

Instead of calling a function which returns session_check , you should change the function which will accept a completion block , and when the data task is completed you can call the completion block with session_check data

check this https://stackoverflow.com/a/30401560/3295851 on how to create methods with completion handler

ManuRaphy
  • 361
  • 1
  • 13