我试图将一个对象从一个视图控制器传递到另一个视图控制器,并且在调用下一个视图控制器时该对象似乎是空的。我发现其他论坛建议我使用与此类似的东西来传递我的User
对象。
var user: User!
override func viewDidLoad() {
super.viewDidLoad()
oauthswift = OAuth1Swift(
consumerKey: CONSUMER_KEY,
consumerSecret: CONSUMER_SECRET,
requestTokenUrl: "https://api.twitter.com/oauth/request_token",
authorizeUrl: "https://api.twitter.com/oauth/authorize",
accessTokenUrl: "https://api.twitter.com/oauth/access_token"
)
handle = oauthswift.authorize(
withCallbackURL: URL(string: "oauth-swift://oauth-callback/twitter")!,
success: { credential, response, parameters in
print("OAuthToken: \(credential.oauthToken)")
print("OAuthSecret: \(credential.oauthTokenSecret)")
print("User ID: \(parameters["user_id"]!)")
self.user = User(oauthswift: self.oauthswift, consumerKey: CONSUMER_KEY, consumerSecret: CONSUMER_SECRET, oAuthToken: credential.oauthToken, oAuthSecret: credential.oauthTokenSecret)
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let feedViewController = segue.destination as? FeedViewController {
feedViewController.user = self.user
}
}
self.performSegue(withIdentifier: "goToFeed", sender: self)
// Do your request
},
failure: { error in
print(error.localizedDescription)
print(self.handle)
}
)
// Do any additional setup after loading the view, typically from a nib.
}
执行goToFeed
时,User对象为空。我正在闭包中执行初始化,所以在我看来用户应该完全填充。我假设我使用segue函数的方式不正确?任何想法都表示赞赏。
答案 0 :(得分:2)
您误解了如何使用prepare(for:)
。它必须是顶级实例方法,而不是嵌套函数。调用performSegue(withIdentifier:)
后会调用它:
var user: User!
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let feedViewController = segue.destination as? FeedViewController {
feedViewController.user = self.user
}
}
override func viewDidLoad() {
super.viewDidLoad()
oauthswift = OAuth1Swift(
consumerKey: CONSUMER_KEY,
consumerSecret: CONSUMER_SECRET,
requestTokenUrl: "https://api.twitter.com/oauth/request_token",
authorizeUrl: "https://api.twitter.com/oauth/authorize",
accessTokenUrl: "https://api.twitter.com/oauth/access_token"
)
handle = oauthswift.authorize(
withCallbackURL: URL(string: "oauth-swift://oauth-callback/twitter")!,
success: { credential, response, parameters in
print("OAuthToken: \(credential.oauthToken)")
print("OAuthSecret: \(credential.oauthTokenSecret)")
print("User ID: \(parameters["user_id"]!)")
self.user = User(oauthswift: self.oauthswift, consumerKey: CONSUMER_KEY, consumerSecret: CONSUMER_SECRET, oAuthToken: credential.oauthToken, oAuthSecret: credential.oauthTokenSecret)
self.performSegue(withIdentifier: "goToFeed", sender: self)
// Do your request
},
failure: { error in
print(error.localizedDescription)
print(self.handle)
}
)
// Do any additional setup after loading the view, typically from a nib.
}