我是Swift的新手,也是JSON和REST的新手。我尝试验证用户传递的凭据并验证凭据是否有效,然后将一些JSON数据打印到屏幕上。我在网上找到的关于这个的一切似乎都涉及简单的带有api密钥的json api url而没有任何凭据。
基本上我有这样的网址:https://ipaddresshere/yii_entry.php/rest/info 我将成为用户名,例如:Bob和密码,例如:examplePass。
如果有人能够迅速向我展示一个如何通过身份验证获取数据的例子,或者指出我的方向很好。谢谢!
答案 0 :(得分:2)
此登录请求和常规帖子。这依赖于一个名为SwiftyJSON的文件。我建议您下载它并将其添加到您的项目中以进行任何JSON解析。 https://github.com/SwiftyJSON/SwiftyJSON。尝试下载名为postman的chrome浏览器扩展程序以使用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是获取请求的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 :)
})