在 swift 4.1 中使用 httpMethod (POST) 调用 Web 服务

calling a web service with httpMethod (POST) in swift 4.1

先说下view controller(页面设计)。我添加了一个按钮和一个标签。我为按钮创建了一个函数。这是 ViewController.swift 文件:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var btnHitWebService: UIButton!
    @IBOutlet weak var lblResult: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func btnHitWebServiceClick(_ sender: Any) {
        if (getTokenWithPostMethod() == true)
        {
            lblResult.text = "yes, we get token: " + g_token
        }
        else
        {
            lblResult.text = "there is an error, please try again later"
        }
    }

    func getTokenWithPostMethod() -> Bool{

        var funcResult = false

        var request = URLRequest(url: URL(string: "https://apiABCDEFG.com/token")!)
        request.httpMethod = "POST"
        let postString = "grant_type=password&username=ABCDEF&password=ABCDEF"
        request.httpBody = postString.data(using: .utf8)
        request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let task = URLSession.shared.dataTask(with: request)
        {
            data, response, error in
            guard let data = data, error == nil else
            {
                // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200
            {
                // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }

            do
            {
                if let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
                {
                    g_token = (jsonObject["access_token"] as? String)!
                    print(g_token)
                    g_token_type = (jsonObject["token_type"] as? String)!
                    print("\n")
                    print(g_token_type)
                    funcResult = true ;
                }
            }
            catch let error as NSError
            {
                print(error)
            }
        }

        task.resume()
        return funcResult
    }
}

这是我的问题:当我单击按钮时,它在 Xcode(打印)的输出屏幕中为我提供了一个标记,但 getTokenWithPostMethod() 方法 return 是错误的。为什么它 return 是错误的?在调试过程中,它从let task =跳转到task.resume()。谢谢! (顺便说一下,我不能分享正确的 link、用户名和密码。我希望这 3 个不是解决这个问题所必需的)

它是 returning false 因为,你在启动时设置了 var funcResult = false,所以在 URLSession 请求服务器和 return 一些数据响应之前,你的函数 returns funcResult 值。

您可以在 URLSession 任务主体中添加以下代码,在 try catch 之后立即添加,而不是将其添加到 btnHitWebServiceClick 中:

if (getTokenWithPostMethod() == true)
    {
        lblResult.text = "yes, we get token: " + g_token
    }
    else
    {
        lblResult.text = "there is an error, please try again later"
    }

您正在拨打 API 电话。 return 值需要时间。这里 return 语句不会等待响应。您应该使用闭包或委托。您可以尝试给定的代码:

func getTokenWithPostMethod(handler: @escaping (_ funcResult: Bool) -> Void){

    var request = URLRequest(url: URL(string: "https://apiABCDEFG.com/token")!)
    request.httpMethod = "POST"
    let postString = "grant_type=password&username=ABCDEF&password=ABCDEF"
    request.httpBody = postString.data(using: .utf8)
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = URLSession.shared.dataTask(with: request)
    {
        data, response, error in
        var funcResult = false

        if error == nil, let data = data {
            do
            {
                if let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
                {
                    g_token = (jsonObject["access_token"] as? String)!
                    print(g_token)
                    g_token_type = (jsonObject["token_type"] as? String)!
                    print("\n")
                    print(g_token_type)
                    funcResult = true
                }
            }
            catch let error as NSError
            {
                print(error)
            }
        }
        // edited
        DispatchQueue.main.async {
            handler(funcResult)
        }
    }
    task.resume()
}

这将在响应到来后return。将该方法的调用替换为 :

@IBAction func btnHitWebServiceClick(_ sender: Any) {

    getTokenWithPostMethod { (flag) in
        if flag {
            lblResult.text = "yes, we get token: " + g_token
        } else {
            lblResult.text = "there is an error, please try again later"
        }
    }
}

详情请visit