Swift - Use of unresolved identifier 'self' - from Closure in a Class
Rahul's explanation is correct, but the suggested answer is ever so slightly incomplete.
Here is a complete solution:
Declare the
doSomething
property aslazy
as Rahul suggested. A lazy stored property is a property whose initial value is not calculated until the first time it is used. In other words this closure will not be evaluated until the doSomething property is called at run-time, at which pointself
is guaranteed to exist. See Lazy Stored Properties in the Swift Programming Language for more details.Add a type annotation to the
doSomething
property so the compiler doesn't have to infer the type at compile time, which apparently it can't do because the closure includesself
. See Type Safety and Type Inference in the Swift Programming Language for more details.
So the complete declaration is:
...
lazy var doSomething: (Data?, URLResponse?, Error?) -> Void = { (data: Data?, response: URLResponse?, error: Error?) -> Void in
...
ps. Welcome to Swift programming! It's a fantastic language and really fun. I hope you enjoy it as much as I do.
Use of Unresolved Identifier 'self' in swift
The formatting of the code makes it challenging to see what's going on, but it looks like the function audioStreamingDidLogin(:SPTAudioStreamingController!) is not a class function. Maybe global, because it's declared outside the class where self is available.
You may be able to:
- move it into the class
- pass some instance of ViewController into the method as a parameter
Moving it into the class makes most sense to me.
Edit: Fix code
class ViewController: UIViewController, SPTAudioStreamingPlaybackDelegate, SPTAudioStreamingDelegate {
// Variables
var auth = SPTAuth.defaultInstance()!
var session:SPTSession!
// Initialzed in either updateAfterFirstLogin: (if first time login) or in viewDidLoad (when there is a check for a session object in User Defaults
var player: SPTAudioStreamingController?
var loginUrl: URL?
// Outlets
@IBOutlet weak var loginSpotify: UIButton!
@IBOutlet weak var testLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
func setup () {
// insert redirect your url and client ID below
let redirectURL = "splitter-app://callback" // put your redirect URL here
let clientID = "client id goes here" // put your client ID here
auth.redirectURL = URL(string: redirectURL)
auth.clientID = "client id goes here"
auth.requestedScopes = [SPTAuthStreamingScope, SPTAuthPlaylistReadPrivateScope, SPTAuthPlaylistModifyPublicScope, SPTAuthPlaylistModifyPrivateScope]
loginUrl = auth.spotifyWebAuthenticationURL()
print("test")
}
func initializePlayer(authSession:SPTSession){
if self.player == nil {
self.player = SPTAudioStreamingController.sharedInstance()
self.player!.playbackDelegate = self
self.player!.delegate = self
try! player!.start(withClientId: auth.clientID)
self.player!.login(withAccessToken: authSession.accessToken)
}
}
func updateAfterFirstLogin () {
loginSpotify.isHidden = true
let userDefaults = UserDefaults.standard
if let sessionObj:AnyObject = userDefaults.object(forKey: "SpotifySession") as AnyObject? {
let sessionDataObj = sessionObj as! Data
let firstTimeSession = NSKeyedUnarchiver.unarchiveObject(with: sessionDataObj) as! SPTSession
self.session = firstTimeSession
initializePlayer(authSession: session)
}
}
func initializaPlayer(authSession:SPTSession){
if self.player == nil {
self.player = SPTAudioStreamingController.sharedInstance()
self.player!.playbackDelegate = self
self.player!.delegate = self
try! player?.start(withClientId: auth.clientID)
self.player!.login(withAccessToken: authSession.accessToken)
}
}
func audioStreamingDidLogin(_ audioStreaming: SPTAudioStreamingController!) {
// after a user authenticates a session, the SPTAudioStreamingController is then initialized and this method called
print("logged in")
self.player?.playSpotifyURI("spotify:track:58s6EuEYJdlb0kO7awm3Vp", startingWith: 0, startingWithPosition: 0, callback: { (error) in
if (error != nil) {
print("playing!")
}
})
}
}
Use of unresolved identifier self
This situation happens when self
is not defined, please make sure that you are trying to add startMonitoring()
function to a class, extension or struct's scope.
Use of unresolved identifier 'self' (CoreData)
Remove the } on this line
@IBOutlet weak var Table_label: UILabel!
}
and put another } at the end of this file.
Related Topics
How to Add a Show More/Show Less Uibutton to Control Uitextview
How to Perform Face Detection in Swift
How to Cast from Uint16 to Nsnumber
Set Uitextfield Placeholder Color Programmatically
Swift Firestore Check If Documents Exists
Modifying an Array Passed as an Argument to a Function in Swift
Saving a Codable Struct to Userdefaults with Swift
Type Check Operator (Is) for Check VS Homogenous Protocol: Why Can This Be Done for Optionals
Does Swift Optimise Chained Creation and Copy of Structs
Saving Coredata to a Web Server with Swift 3.0
Sharing Highscore with Social Media
What Does "Arg = Exploded" Mean in Swift Crash Log
Ambigious Reference to Member Request() Issues with Alamofire After Migration to Swift 3
Implemented Helper App But Does Not Launch on Login