我有以下代码,应该将用户名和密码发送到Web服务,作为回报,我得到一个整数:
payload
在我的函数中,我需要添加两个参数,我正在尝试这一行:
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()
}
我在运行此操作时从我的网络服务获得以下响应
可选(“缺少参数:密码。\ r \ n”)
我显然没有正确地将参数附加到请求中,但我不确定我做错了什么。
答案 0 :(得分:1)
最好避免使用显式展开选项(使用!
),而使用guard let
代替文本i UITextField
。
为什么不分成两个方法attemptLogin
和login
,这些方法可能会在登录完成时执行代码执行时关闭?也许封闭可以采用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)")
}
}
}
免责声明:尚未测试上述代码,但希望它能够编译(至少只需进行非常小的更改)。