Swift - 网络服务的多个参数

Swift - Multiple Parameters to webservice

我有以下代码应该将用户名和密码发送到网络服务,在 return 我得到一个整数:

 func attemptLogin() {

        let url:URL = URL(string: endpoint+"/LoginNew")!
        let session = URLSession.shared

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

        let postString = "username="+txtUsername.text! + "; password="+txtPassword.text!
        request.httpBody = postString.data(using: String.Encoding.utf8)

        let task = session.dataTask(with: request as URLRequest) {
            (
            data, response, error) in

            guard let data = data, let _:URLResponse = response, error == nil else {
                print("error")
                return
            }

            let dataString =  String(data: data, encoding: String.Encoding.utf8)
            print(dataString)

        }

        task.resume()

    }

在我的函数中,我需要添加两个参数,我正在尝试在这一行中做:

 let postString = "username="+txtUsername.text! + "; password="+txtPassword.text!
        request.httpBody = postString.data(using: String.Encoding.utf8)

当我 运行 但是

时,我的网络服务收到以下响应

Optional("Missing parameter: password.\r\n")

我显然没有正确地将参数附加到请求中,但我不确定我做错了什么。

最好避免使用显式解包选项(使用 !),使用 guard let 作为文本 i UITextFields。

为什么不分成两个方法,attemptLoginlogin,这可能会导致代码在登录完成时执行闭包?也许闭包可以采用 Result 枚举。

像这样:

typealias Done = (Result) -> Void

enum MyError: Error {
    case unknown
}

enum Result {
    case success(String)
    case failure(MyError)

    init(_ error: MyError) {
        self = .failure(error)
    }

    init(_ dataString: String) {
        self = .success(dataString)
    }
}

func login(username: String, password: String, done: Done? = nil) {
    let session = URLSession.shared
    guard 
        let url = URL(string: endpoint+"/LoginNew"),
    else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
    let postString = "username=\(username)&password=\(password)"
    request.httpBody = postString.data(using: String.Encoding.utf8)
    let task = session.dataTask(with: request) {
        (data, response, error) in
        guard let data = data else { done?(Result(.unknown)); return }
        let dataString =  String(data: data, encoding: String.Encoding.utf8)
        done?(Result(dataString))
    }

    task.resume()
}

func attemptLogin() {
    guard 
        let username = txtUsername.text,
        let password = txtPassword.text
    else { return }

    login(username: username, password: password) {
        result in
        swicth result {
            case .success(let dataString):
                print(dataString)
            case .failure(let error):
                print("Failed with error: \(error)")
        }
    }
}

免责声明:尚未测试上面的代码,但希望它可以编译(至少有非常小的更改)。