Swift:执行顺序,REST API

时间:2019-12-09 12:41:39

标签: ios swift

我的学校项目需要帮助。
为什么在doAPI()之前打印print(segueShouldOccur)。 当我实际在print(seagueShouldOccur)之前调用doApi()时。 我说的是方法:shouldPerformSegue。 Rest Api确实有效(已经测试)。

class ViewController: UIViewController {
    var loginArr = [String]()
    @IBOutlet weak var _output: UILabel!

    @IBOutlet weak var _username: UITextField!

    @IBOutlet weak var _password: UITextField!

    @IBAction func doLogin(_ sender: Any) {
        loginArr.removeAll()
        let username = _username.text;
        let password = _password.text;
        loginArr.append(username!);
        loginArr.append(password!);
        self._output.text = username;
    }

    func doApi() -> Bool{
        let headers = [
            "cache-control": "no-cache",
            "postman-token": "6f8a-12c6-87a1-ac0f25d6385a"
        ]
        let url = "https://projects2018.sz-ybbs.ac.at/~szmed/indyapp/indyapi.php?func=0&user=" + _username.text! + "&pass=" + _password.text!

        let request = NSMutableURLRequest(url: NSURL(string: url)! as URL,
            cachePolicy: .useProtocolCachePolicy,
            timeoutInterval: 10.0)

        var check = false;

        request.httpMethod = "GET"
        request.allHTTPHeaderFields = headers

        let session = URLSession.shared
        let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
            if error == nil && data != nil {
                do {
                    let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject]
                   //do your stuff
                    print(json);
                    check = true;

                } catch {
                }
            }
            else if error != nil
            {
            }
        }).resume()
        return check;
        }

     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
           let DashboardC = segue.destination as! DashboardController
            DashboardC.receivedStringArr = loginArr
           }

    override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
        if identifier == "performSegueLogin" { // you define it in the storyboard (click on the segue, then Attributes' inspector > Identifier
            var segueShouldOccur = doApi()
            if (!segueShouldOccur){
                print("1 - false");
                print(segueShouldOccur);
                return false;
            }else{
                print("2 - true");
                print(segueShouldOccur);
                return true;
            }
        }
        return false;
    } 
}

1 个答案:

答案 0 :(得分:0)

session.dataTask是异步的。如果您想知道您的api调用何时完成,可以使用如下的完成处理程序:

func doApi(completion : @escaping (Bool?,Error?) -> ()) {
let headers = [
"cache-control": "no-cache",
"postman-token": "6f8a-12c6-87a1-ac0f25d6385a"
]
let url = "https://projects2018.sz-ybbs.ac.at/~szmed/indyapp/indyapi.php?func=0&user=" + _username.text! + "&pass=" + _password.text!

 let request = NSMutableURLRequest(url: NSURL(string: url)! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)

var check = false;

request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if error == nil && data != nil {
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject]
           //do your stuff
            print(json);
            check = true;
        } catch {
        }
        completion(true,nil)

    }
    else if error != nil
    {
        completion(false,error)
    }
}).resume()
return check;
}

然后您可以像这样调用函数:

doApi { (isSuccess, errorMessage) in
if isSuccess {
    // perform your operations
} else {
    print(errorMessage?.localizedDescription ?? "Some error occured")
}
}