Swift的新手并尝试为我的应用编写登录屏幕。
我的控制器:
class Api {
func authenticate(username: String, password: String) -> Bool {
var params = [String: String]()
params["username"] = username
params["password"] = password
params["grant_type"] = "password"
var headers = [String: String]()
headers["Content-Type"] = "application/x-www-form-urlencoded"
post("authenticate", params: params, headers: headers) {data, response in
// do something
}
}
func post(location: String, params: [String: String], headers: [String: String], callback: ((data: NSString!, response: NSHTTPURLResponse) -> Void)) {
let request = NSMutableURLRequest()
let session = NSURLSession.sharedSession()
request.URL = NSURL(string: Configuration.apiBaseUrl + location)
request.HTTPMethod = "POST"
request.HTTPBody = NSString(string: getPostBody(params)).dataUsingEncoding(NSUTF8StringEncoding)
request.addValue("Basic " + Configuration.apiAuthorization, forHTTPHeaderField: "Authorization")
for (key, value) in headers {
request.addValue(value, forHTTPHeaderField: key)
}
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let data = NSString(data: data!, encoding: NSUTF8StringEncoding)
let httpResponse = response as! NSHTTPURLResponse
callback(data: data, response: httpResponse)
return
})
task.resume()
}
}
Api课程:
{{1}}
由于我计划在身份验证后添加更多API方法,因此我需要通用的POST / PUT / GET / DELETE方法。我试图理解如何在Swift中最好地设置回调,因此authenticate方法中的post调用可以返回true / false并在UI线程上显示为对话框。现在不允许在authenticate方法中的post调用中返回布尔值,因为它期望Void。
我熟悉nodejs中的回调并试图掌握这一点。任何暗示最好的方法是什么?