gpt4 book ai didi

swift - 在 Swift 中以编程方式在 View 之间传递 OAuth token

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

我坚持尝试将变量从一个 View 传递到另一个 View 。我故意在没有 Storyboard的情况下以编程方式完成这一切。

ViewController 创建有一个 UIButton,当按下它时调用 AuthoriseController。

AuthoriseController 然后加载一个 UIWebView,在特定的 URL 处打开它,例如https://foursquare.com/oauth2/authenticate?client_id=xxxxx&response_type=token&redirect_uri=yyyyy

这会加载一个 OAuth 屏幕。用户登录后,控制权返回到 AuthoriseController,我在其中提取重定向 URI 中返回的 access_token。

提取效果很好,我可以拿到 token ,我的问题是我想将 token 返回到我的 ViewController,这样当用户再次按下按钮时,它将可用于 HTTP 请求(在我只是打印 token 的那一刻)。

我的 ViewController 和 AuthoriseController 实现了一个名为 DataProtocol 的协议(protocol),我希望它可以用于在 Controller 之间共享 token 。

View Controller :

import UIKit

class ViewController: UIViewController {

var delegate: DataProtocol? = nil

func setUpView(){
let firstView = UIView()
let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
firstView.setTranslatesAutoresizingMaskIntoConstraints(false)
firstView.backgroundColor = UIColor(red: 0.75, green: 0.75, blue: 0.1, alpha: 1.0)
view.addSubview(firstView)
setUpButton(button)
firstView.addSubview(button)
setUpConstraints(firstView, button)
}

func setUpConstraints(firstView: UIView, _ button: UIButton) {
let viewsDictionary = ["firstView":firstView,"button":button]
let metricsDictionary = ["firstViewHeight":1334.0,"viewWidth":750.0 ]
let firstViewHeightConstraintH:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:[firstView(viewWidth)]", options: NSLayoutFormatOptions(0), metrics: metricsDictionary, views: viewsDictionary)
let firstViewHeightConstraintV:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:[firstView(firstViewHeight)]", options: NSLayoutFormatOptions(0), metrics: metricsDictionary, views: viewsDictionary)

firstView.addConstraints(firstViewHeightConstraintH)
firstView.addConstraints(firstViewHeightConstraintV)

let buttonConstraintH:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-150-[button(>=80)]", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: viewsDictionary)
let buttonConstraintV:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-300-[button]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)

firstView.addConstraints(buttonConstraintH)
firstView.addConstraints(buttonConstraintV)
}

func setUpButton(button: UIButton) {
button.setTranslatesAutoresizingMaskIntoConstraints(false)
button.setTitle("Authorise", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonPressed", forControlEvents: UIControlEvents.TouchUpInside)
button.backgroundColor = UIColor.blueColor()
button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
}

override func shouldAutorotate() -> Bool {
return false
}

func buttonPressed(){
let ac = AuthoriseController()
self.presentViewController(ac, animated: true, completion: nil)
println("token in ViewController.buttonPressed: [\(self.delegate?.token)]")
}

override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: 0.9, green: 0.9, blue: 1, alpha: 1.0)
setUpView()
}
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.All.toRaw())
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

授权 Controller :

import UIKit
import WebKit

class AuthoriseController: UIViewController, UIWebViewDelegate, DataProtocol {

var token: String = ""

let AUTH_URL = "https://foursquare.com/oauth2/authenticate?client_id=";
let RESP_TYPE_AND_KEY_AND_TOKEN = "&response_type=token&redirect_uri=";
let REDIRECT_URI : String = "ZZZZZZZZ";
let CLIENT_ID : String = "XXXXXXX";

var webview: UIWebView = UIWebView()

override func viewDidLoad() {
super.viewDidLoad()
var myViewController = ViewController()

self.webview.frame = self.view.bounds
self.webview.delegate = self
self.view.addSubview(self.webview)

var url: NSURL = NSURL.URLWithString(AUTH_URL + CLIENT_ID + RESP_TYPE_AND_KEY_AND_TOKEN + REDIRECT_URI)
var urlRequest: NSURLRequest = NSURLRequest(URL: url)
self.webview.loadRequest(urlRequest)
}

func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
token = getToken(request.URL.absoluteString!)
println("token in AuthoriseController.webView: [\(token)]")
if(!token.isEmpty) {
self.dismissViewControllerAnimated(true, completion: nil)
}
return true
}

func getToken(url: String) -> String {
var token = ""
if url.rangeOfString("#access_token") != nil{
token = url.componentsSeparatedByString("=").last!
}
return token
}
}

这是数据协议(protocol):

import Foundation

protocol DataProtocol {
var token : String { get set }
}

当我这样做时:

  1. 启动应用
  2. 按下授权按钮
  3. 登录成功(控制权返回ViewController
  4. 再次按下按钮

输出:我得到这个输出:

token in ViewController.buttonPressed: [nil]
token in AuthoriseController.webView: []
token in AuthoriseController.webView: []
token in AuthoriseController.webView: []
token in AuthoriseController.webView: [VSKRNHJRS3NWPN3EEIYMCSZYJ2YMNSH4GBXNQFL1EMYLJ5TO]
token in ViewController.buttonPressed: [nil]
token in AuthoriseController.webView: []
token in AuthoriseController.webView: [VSKRNHJRS3NWPN3EEIYMCSZYJ2YMNSH4GBXNQFL1EMYLJ5TO]

我希望在第二次出现 ViewController.buttonPressed 时看到 token ,而不是 NIL。

谁能看出我哪里出错了?任何帮助是极大的赞赏!史蒂夫

最佳答案

看起来委托(delegate)已正确连接,但您并未向其发送 token 。在 AuthoriseController 中,您需要为委托(delegate)设置 token :

func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
token = getToken(request.URL.absoluteString!) // sets the token in the AuthoriseController
println("token in AuthoriseController.webView: [\(token)]")
if(!token.isEmpty) {
// pass the token to the delegate
self.delegate?.token = token
self.dismissViewControllerAnimated(true, completion: nil)
}
return true
}

关于swift - 在 Swift 中以编程方式在 View 之间传递 OAuth token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27028516/

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