我在swift应用程序中使用Heimdallr.swift存储库以OAuth2密码授权登录。但在获得“成功”消息后,我仍然无法访问受保护的资源。有谁知道如何保存您收到的令牌或问题可能是什么?
@IBAction func loginButton(sender: UIButton) {
let username: String = usernameTextfield.text!;
let password: String = passwordTextfield.text!;
let tokenURL = NSURL(string: "http://challyme.dk:8888/index.php/api/v1.1/oauth/access_token")!
let identifier = "id0"
let secret = "secret0"
let credentials = OAuthClientCredentials(id: identifier, secret: secret)
let heimdall = Heimdallr(tokenURL: tokenURL, credentials: credentials)
heimdall.requestAccessToken(username: username, password: password) { result in
switch result {
case .Success:
self.callUserInfo(heimdall)
dispatch_async(dispatch_get_main_queue()) {
let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let vc : UIViewController = mainStoryboard.instantiateViewControllerWithIdentifier("LogedInView") as UIViewController
self.presentViewController(vc, animated: true, completion: nil)
}
case .Failure:
dispatch_async(dispatch_get_main_queue()) {
print("Wrong password or username")
let alertView = UIAlertController(title: "Alert", message: "You entered the wrong username or password", preferredStyle: .Alert)
alertView.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
self.presentViewController(alertView, animated: true, completion: nil)
}
}
}
}
应显示受保护资源的方法:
func callUserInfo(heimdall: Heimdallr) {
let urlPath = "http://linkToResources"
let url: NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
heimdall.authenticateRequest(request, completion: { result in
switch result {
case .Success(let request):
let task = session.dataTaskWithRequest(request) { data, response, error in
let json = JSON(data: data!);
print(response!.description);
if response != nil {
print(json);
} else {
print(json[999].error) // "Array[999] is out of bounds"
}
}
task.resume()
case .Failure:
print("failure")
}
})
}
祝你好运 安德斯B.克里斯滕森