Eban Stern
Eban Stern

Reputation: 1

Accessing a string variable from another View in Swift?

I need to get the SpotifyAccessToken from my LoginViewController to my GuestPartyViewController.

 class LoginViewController: UIViewController {

 @IBOutlet weak var spotifyLoginBtn: UIButton!

var spotifyId = ""
var spotifyDisplayName = ""
var spotifyEmail = ""
var spotifyAvatarURL = ""
var spotifyAccessToken = ""

override func viewDidLoad() {
    super.viewDidLoad()
    spotifyLoginBtn.layer.cornerRadius = 10.0
}

And I need to use that variable in the searchURL of my GuestPartyViewController.

     import UIKit
 import Alamofire
 import AVFoundation
 class GuestPartyViewController: UIViewController {


@IBOutlet weak var partyNameLabel: UILabel!
var partyName: String?
@IBOutlet weak var partyDescriptionLabel: UILabel!
var partyDescription: String?
@IBOutlet var searchBar: UISearchBar!
var spotifyAccessToken: String?

var searchURL = "https://api.spotify.com/v1/search?q=Kanye%20West&type=track&access_token=\(spotifyAccessToken)" // The error here is: Cannot use instance member 'spotifyAccessToken' within property initializer; property initializers run before 'self' is available


 class DetailsViewController:UIViewController {

 var spotifyAccessToken: String?
 @IBAction func startPartyButton(_ sender: Any) {
     performSegue(withIdentifier: "startParty", sender: self)
 }
 @IBAction func joinPartyButton(_ sender: Any) {
     performSegue(withIdentifier: "joinPartySeg", sender: self)
 }

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     if(segue.identifier == "startParty") {
     let GuestPartyVC = segue.destination as! GuestPartyViewController 
 // Here is where I get the error
     GuestPartyVC.spotifyAccessToken = spotifyAccessToken
 }
 }

I was thinking about declaring it in the app delegate, but I'm not sure how to do that since it is first declared in the LoginViewController.

Upvotes: 0

Views: 69

Answers (1)

Mo Abdul-Hameed
Mo Abdul-Hameed

Reputation: 6110

After performing login in LoginViewController and getting the token pass it to the next view controller whatever it is, and pass it again from that view controller to `GuestPartyViewController' so that you can use it.

To pass the token you can either pass it by injecting it through the initialiser of the next view controller or by overriding prepare(for:sender:) method like this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Do check for the next view controller and set the value of the token here
}

Upvotes: 1

Related Questions