gpt4 book ai didi

ios - Swift 2 发布和响应代码转换有用的功能

转载 作者:行者123 更新时间:2023-11-28 21:32:43 24 4
gpt4 key购买 nike

我想将参数字符串和 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
}

并返回以下内容:

durum and postTitle with strings.

谢谢。

最佳答案

对于异步方法,如果要返回结果,最好使用完成闭包。

    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)
}

关于ios - Swift 2 发布和响应代码转换有用的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35257942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com