我想将参数字符串和 url 发送到函数,我想返回 JSON 成功和消息字符串。请帮忙。
以下是我的代码:
let postEndpoint:NSString = "http://bla.com/application/login.php?email=(username)&password=(password)"
print(postEndpoint)
guard let url = NSURL(string: postEndpoint as String) else {
print("Error: cannot create URL")
return
}
let urlRequest = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) in
guard let responseData = data else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("error calling GET on /posts/1")
print(error)
return
}
// parse the result as JSON, since that's what the API provides
let post: NSDictionary
do {
post = try NSJSONSerialization.JSONObjectWithData(responseData,
options: []) as! NSDictionary
} catch {
print("error trying to convert data to JSON")
return
}
// now we have the post, let's just print it to prove we can access it
// print("The post is: " + post.description)
// the post object is a dictionary
// so we just access the title using the "title" key
// so check for a title and print it if we have one
if let durum = post["success"] as? String {
print("Success : " + durum)
}
if let postTitle = post["message"] as? String {
print("Message : " + postTitle)
}
})
task.resume()
我想实现这样的事情:
func post(params : Dictionary<String, String>, url : String) {
.... code is here
}
并返回以下内容:
杜伦和带有字符串的后标题。
谢谢。
对于异步方法,如果要返回结果,最好使用完成闭包。
typealias Response = (durum: String, postTitle: String)
typealias Completion = ((Response?, ErrorType?) -> Void)?
func post(params : Dictionary<String, String>, url : String, completion:Completion) {
//.... code is here
completion?((durum, postTitle), nil)
}