gpt4 book ai didi

ios - Swift:REST JSON Get 请求带身份验证

转载 作者:行者123 更新时间:2023-11-28 13:09:38 25 4
gpt4 key购买 nike

我对 Swift 很陌生,对 JSON 和 REST 也很陌生。我尝试验证用户传递的凭据并验证凭据是否有效,然后将一些 JSON 数据打印到屏幕上。我在网上找到的关于此的所有内容似乎都涉及一个简单的 json api url 和一个没有任何凭据的 api key 。

基本上我有这样一个 url:https://ipaddresshere/yii_entry.php/rest/info我将为用户提供一个用户名,例如:Bob 和一个密码,例如:examplePass。

如果有人可以快速向我展示如何通过身份验证获取数据的示例,或者为我指明正确的方向,那就太好了。谢谢!

最佳答案

这个登录请求,和一个普通的帖子。这依赖于一个名为 SwiftyJSON 的文件。我建议您下载它并将其添加到您的项目中以进行任何 JSON 解析。 https://github.com/SwiftyJSON/SwiftyJSON .尝试在 chrome 中下载一个名为 postman 的浏览器扩展来处理 JSON 和 REST。这是登录和通用发布请求的示例发布请求。这些放在模态 swift 文件中。

func loginRequest(username: String!, password: String!, completionHandler: ((NSURLResponse!, JSON, NSError?) -> Void)) {
var request : NSMutableURLRequest = NSMutableURLRequest()
let url: String! = "http://yourRestURL/login/\(username)/\(password)"
println(url)
request.URL = NSURL(string: url)
request.HTTPMethod = "POST"
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) in
var json = JSON(data: data!)
println(json)
completionHandler(response, json, error)
})
}

func postRequest(resourceURL: String!, completionHandler: ((NSURLResponse!, JSON, NSError?) -> Void)) {
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: resourceURL)
request.HTTPMethod = "POST"

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) in
var json = JSON(data: data!)
completionHandler(response, json, error)
})

如果硬要GET:资源URL就是get请求的URL。

func getRequest(resourceURL: String!, completionHandler: ((NSURLResponse!, JSON, NSError?) -> Void)) {
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: resourceURL)
request.HTTPMethod = "GET"

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) in
var json = JSON(data: data!)
completionHandler(response, json, error)
})

}

用法:在您的 VC 中:

 func parseLoginRequest (usernameGiven: String, passwordGiven: String, sender: AnyObject?) {
println("parsing")

modal.loginRequest(usernameGiven, password: passwordGiven) { (response, json, error) in
// parse it :)

})

关于ios - Swift:REST JSON Get 请求带身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31840899/

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