Userdefaults to save switch state - ios

I Have a switch that when turned to "on" will put the music and when the switch is set to "off" the music will resume playing. My problem is that when i leave the view controller the switch will appear as "off" when it is switch "on". The code for my switch is below, I'm not sure what to write in order for the app to remember the switch state, please help.
//
// SecondViewController.swift
// Urban Sphere
//
// Created by Oren Edrich on 9/11/16.
// Copyright © 2016 Oren Edrich. All rights reserved.
//
import Foundation
import UIKit
import SpriteKit
import AVFoundation
var bombSoundEffect: AVAudioPlayer!
var Ghost = SKSpriteNode()
class SecondViewController: UIViewController {
var sw = false
#IBOutlet var mySwitch: UISwitch!
#IBAction func switchpressed(_ sender: AnyObject) {
if mySwitch.isOn{
if bombSoundEffect != nil {
bombSoundEffect.stop()
bombSoundEffect = nil
}
}
else{
let path = Bundle.main.path(forResource: "newmusic.wav", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
bombSoundEffect = sound
sound.numberOfLoops = -1
sound.play()
} catch {
// couldn't load file :(
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}

I found the correct answer and decided to post it incase anyone has the same question.
#IBAction func saveSwitchState(sender: AnyObject) {
var defaults = NSUserDefaults.standardUserDefaults()
if bluetoothSwitch.on {
defaults.setBool(true, forKey: "SwitchState")
} else {
defaults.setBool(false, forKey: "SwitchState")
}
}
and...
override func viewDidLoad() {
super.viewDidLoad()
var defaults = NSUserDefaults.standardUserDefaults()
if (defaults.objectForKey("SwitchState") != nil) {
bluetoothSwitch.on = defaults.boolForKey("SwitchState")
}
}

You want know where to insert the code , I guess.
updata
updata2
Then you can run directly. If it's useful , please UP this answer.
import Foundation
import UIKit
import SpriteKit
import AVFoundation
class SecondViewController: UIViewController {
static let bombSoundEffect = {()->(AVAudioPlayer) in
let path = Bundle.main.path(forResource: "newmusic.wav", ofType:nil)!
let url = URL(fileURLWithPath: path)
return try! AVAudioPlayer(contentsOf: url)
}()
var sw = false
var Ghost = SKSpriteNode()
#IBOutlet var mySwitch: UISwitch!
#IBAction func switchpressed() {
if mySwitch.isOn{
SecondViewController.bombSoundEffect.play()
}else{
SecondViewController.bombSoundEffect.stop()
}
//************* save status *************
UserDefaults.standard.set(mySwitch.isOn, forKey: "SwitchStatus");
}
override func viewDidLoad() {
super.viewDidLoad()
mySwitch.addTarget(self, action: #selector(switchpressed), for: .valueChanged)
//************* load status *************
mySwitch.isOn = UserDefaults.standard.bool(forKey: "SwitchStatus");
switchpressed()
}
}

I have a similar situation to yours, and I just use UserDefaults. Here's a step-by-step guide on how to do it.
Create a variable like the following example. This will set the default setting and store the state of the check box for use later:
var musicSetting = UserDefaults().string(forKey: "Music") ?? "On"
In your viewDidLoad, add an if statement that will check whether the Check Box should be On or Off, like this:
if musicSetting == "On" {
theNameOfYourSwitch.isOn = false
} else {
theNameOfYourSwitch.isOn = true
}
In the IBAction property for your check box, add an if statement like the following that will save your Setting, depending on what it is:
if theNameOfYourCheckbox.state == NSOnState {
UserDefaults().set("On", forKey: "Music")
} else {
UserDefaults().set("Off", forKey: "Music")
}
Here's a screenshot that might help:

If you want to save the state of Switch in user default, then can use the
native method
UserDefaults.standard.set(_ value: Bool, forKey defaultName: String)
Like this
UserDefaults.standard.set(mySwitch.isOn, forKey: "SwitchStatus");
UserDefaults.standard.synchronize();
While fetching switch status just use
let status = UserDefaults.standard.bool(forKey: "SwitchStatus");
UPDATE :
#IBAction func switchpressed(_ sender: AnyObject) {
UserDefaults.standard.set(mySwitch.isOn, forKey: "SwitchStatus");
if mySwitch.isOn{
if bombSoundEffect != nil {
bombSoundEffect.stop()
bombSoundEffect = nil
}
}
else{
let path = Bundle.main.path(forResource: "newmusic.wav", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
bombSoundEffect = sound
sound.numberOfLoops = -1
sound.play()
} catch {
// couldn't load file :(
}
}
}
Hope it helps
Happy coding ...

Related

Use of Unresolved Identifier 'self' in swift [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Here is the code:
import UIKit
import SafariServices
import AVFoundation
import AWSAuthCore
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!")
}
})
}
The error is on line 91. Xcode says:
"Use of unresolved identifier 'self'"
however I have used that same variable in multiple different places in the code and it is declared at the top of the class. Why is it giving me an error on this specific line? I have tried making it a lazy variable as other people online have suggested, however Xcode tells me lazy variables need to be initialized and I am not sure how to do that.
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!")
}
})
}
}

How to count number of contacts in swift?

how to count number of contacts in swift
,i am very new to this ios platform i just wanted know how to access contact and count it. any valid inputs will be appreciated.
//
// ViewController.swift
// test1
//
// Created by Lakshmi Kanth N on 6/23/17.
// Copyright © 2017 Lakshmi Kanth N. All rights reserved.
//
import UIKit
import Contacts
import ContactsUI
import AddressBook
class ViewController: UIViewController, CNContactPickerDelegate{
#IBOutlet var label: UILabel!
#IBOutlet var click: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]
// The container means
// that the source the contacts from, such as Exchange and iCloud
var allContainers: [CNContainer] = []
do {
allContainers = try contactStore.containersMatchingPredicate(nil)
} catch {
print("Error fetching containers")
}
print (allContainers.count)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func obclick(_ sender: UIButton) {
let entieyType = CNEntityType.contacts
let authStatus = CNContactStore.authorizationStatus(for: entieyType)
if authStatus == CNAuthorizationStatus.notDetermined{
let contactStore = CNContactStore.init()
contactStore.requestAccess(for: entieyType, completionHandler: { (success, nil) in
if success {
self.openContacts()
}
else {
print("NOT")
}
})
}
else if authStatus == CNAuthorizationStatus.authorized{
self.openContacts()
}
}
func openContacts (){
let contactPicker = CNContactPickerViewController.init()
contactPicker.delegate = self
self.present(contactPicker, animated: true, completion: nil)
}
func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
picker.dismiss(animated: true) {
}
}
func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
}
}
above is my code which is used to access the contacts but i need to have a count of them
if item.isKeyAvailable(CNContactPhoneNumbersKey){
let phoneNOs=item.phoneNumbers
print("Phone No count \(phoneNOs.count)")
}
// You may add more "keys" to fetch referred to official documentation
let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)]
// The container means
// that the source the contacts from, such as Exchange and iCloud
var allContainers: [CNContainer] = []
do {
allContainers = try contactStore.containersMatchingPredicate(nil)
} catch {
print("Error fetching containers")
}
print (allContainers.count)
if u want to check for valid input for searching
var contacts: [CNContact] = []
for container in allContainers {
let fetchPredicate = CNContact.predicateForContactsInContainerWithIdentifier(container.identifier)
do {
let containerResults = try contactStore.unifiedContactsMatchingPredicate(fetchPredicate, keysToFetch: keysToFetch)
// Put them into "contacts"
contacts.appendContentsOf(containerResults)
} catch {
print("Error fetching results for container")
}
}
print (containerResults.count)

Having problems with saving and loading in Swift 3.0 iOS 10

I'm really new to the Swift and iOS programming scene and I am trying to learn a bunch of things. For this app, I want to save and load just one integer, but I am having problems, as everything I found on stack overflow and the Internet just doesn't seem to work on Swift 3. The app crashes immediately, it breaks on:
#IBOutlet weak var StaticLabel: UILabel!
It says "Thread 1: breakpoint 3.5" . Any help and tips would be very much appreciated :)
import UIKit
import AVFoundation
var player: AVAudioPlayer?
var number = 0
class ViewController: UIViewController {
#IBOutlet weak var StaticLabel: UILabel!
#IBOutlet weak var NumberLabel: UILabel!
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
Load()
}
func Load()
{
number = defaults.integer(forKey: "Save")
NumberLabel.text = String(number)
}
func playSound()
{
let path = Bundle.main.path(forResource: "RightYouAre.mp3", ofType: nil)
let url = URL(fileURLWithPath: path!)
do {
let sound = try AVAudioPlayer(contentsOf: url)
player = sound
sound.play()
}
catch {
// couldn't load file :(
}
}
#IBAction func Minus(_ sender: AnyObject) {
number = number - 1
NumberLabel.text = String(number)
defaults.set(number, forKey: "Save")
}
#IBAction func Plus(_ sender: UIButton) {
playSound()
number = number + 1
NumberLabel.text = String(number)
defaults.set(number, forKey: "Save")
}
}
your line of code
number = defaults.integer(forKey: "Save")
user defaults integer for key Save is nil, actually this key does not exist at all in the user defaults
before you load this integer from user defaults , it has to be set first
if defaults.object(forKey: "Save") != nil { number = defaults.integer(forKey: "Save") }
this will make sure the object exists in the user defaults before getting it's value
finally your load function should be
func Load()
{
if defaults.object(forKey: "Save") != nil
{
number = defaults.integer(forKey: "Save")
NumberLabel.text = String(number)
}
}
You need to add null handling to the load function as first time there
will be no value for the key "save" in your UserDefaults.
func Load()
{
if let number = defaults.integer(forKey: "Save")
{
self.number = number
NumberLabel.text = String(number)
}
}

enabling button in swift code

I begin swift and i'm making an app ( a little game).
The buttons of levels 2,... are not enabled because the user dont yet win the level 1 when the user install the application. then I want these buttons enabled everytime the user won the level. I wrote this in a file:
class levelList: UIViewController {
#IBOutlet var blvl1: UIButton!
#IBOutlet var blvl2: UIButton!
#IBOutlet var blvl3: UIButton!
var lvlWon1: Bool = false {
didSet {
blvl2?.enabled = lvlWon1
}
}
var lvlWon2: Bool = false {
didSet {
blvl3?.enabled = lvlWon2
}
}
let lvl1Default = NSUserDefaults.standardUserDefaults()
let lvl2Default = NSUserDefaults.standardUserDefaults()
override func viewDidLoad() {
if (lvl1Default.objectForKey("lvlWon1") != nil){
lvl1Default.setBool(true, forKey: "lvlWon1")
lvlWon1 = lvl1Default.valueForKey("lvlWon1") as! Bool!
}
else{
lvl1Default.setBool(false, forKey: "lvlWon1")
lvlWon1 = lvl1Default.valueForKey("lvlWon1") as! Bool!
}
//
if (lvl2Default.objectForKey("lvlWon2") != nil){
lvl2Default.setBool(true, forKey: "lvlWon2")
lvlWon2 = lvl2Default.valueForKey("lvlWon2") as! Bool!
}
else{
lvl2Default.setBool(false, forKey: "lvlWon2")
lvlWon2 = lvl2Default.valueForKey("lvlWon2") as! Bool!
}
}
}
and this in an other file:
class lvl1: UIViewController {
var levelList = levelList()
#IBOutlet var bNext: UIButton!
#IBAction func nextlvl(sender: UIButton) {
levelList.lvlWon1 = true
levelList.lvlWon1 = levelList.lvl1Default.valueForKey("lvlWon1") as! Bool!
let lvl1Default = NSUserDefaults.standardUserDefaults()
lvl1Default.setValue(listeNiveaux.lvlWon1, forKey:"lvlWon1")
lvl1Default.synchronize()
}
//my problem is that all work finely when I wrote:
var lvlWon1: Bool = false {
didSet {
blvl2?.enabled = lvlWon1
}
}
so when i won the lvl 1, the level2 button is enabled, but when i add
var lvlWon2: Bool = false {
didSet {
blvl3?.enabled = lvlWon2
}
}
when I win the level1, the blvl2 and the blvl3 are enabled, I don't know why
I think it's because i save the data of all blvl but i'm not sure.
thanks in advance and really sorry for my english, it's not my first language.
The problem is because you are calling NSUserDefaults.standardUserDefaults() twice, in order to fix it you could:
Create a new variable named defaults and store the user defaults instance, so that this let lvl1Default = NSUserDefaults.standardUserDefaults()
let lvl2Default = NSUserDefaults.standardUserDefaults() becomes let defaults = NSUserDefaults.standardUserDefaults()
Use that new variable replacing the previous lvl1Default and lvl2Default on viewDidLoad (and do not forget to call super)
override func viewDidLoad() {
super.viewDidLoad()
if (defaults.objectForKey("lvlWon1") != nil){
defaults.setBool(true, forKey: "lvlWon1")
lvlWon1 = defaults.valueForKey("lvlWon1") as! Bool
}
else{
defaults.setBool(false, forKey: "lvlWon1")
lvlWon1 = defaults.valueForKey("lvlWon1") as! Bool
}
//
if (defaults.objectForKey("lvlWon2") != nil){
defaults.setBool(true, forKey: "lvlWon2")
lvlWon2 = defaults.valueForKey("lvlWon2") as! Bool
}
else{
defaults.setBool(false, forKey: "lvlWon2")
lvlWon2 = defaults.valueForKey("lvlWon2") as! Bool
}
}
Edit after 2016-08-10 comment:
On my first attempt to provide an answer to your problem, I tried to isolate the problem and I succesfully managed to recreate it without considering the code on the lvl1 class. Since this did not solved your issue, I made a second attempt taking the nextlvl function in consideration.
On this function, there is another NSUserDefaults.standardUserDefaults() call. The first thing I would do is to make the 'defaults' constant (explained previously) as a global variable so that you can access it everywhere. (in case you need more info about this, you could check this answer)
Another thing I noticed is the call to synchronize() which is deprecated.
So, after moving the defaults constant to somewhere global, I think what you meant to do on the nextlvl function should be:
#IBAction func nextlvl(sender: UIButton) {
lvlWon1 = true
defaults.setBool(true, forKey: "lvlWon1");
}
Edit 2:
As a side note:
When you are casting lvlWon2 = defaults.valueForKey("lvlWon2") as! Bool! you do not need to place ! in the type, as in as! Bool! you just need as! Bool
Bool is a boolean type that cannot be null whereas Bool! means a boolean type that is implicitly unwrapped and Bool? means a boolean type needs to be unwrapped.
If you wish to read more about wrappers, check The Swift Programming Language reference
You can also use defaults.boolForKey("lvlWon2") which gives you the result as a Bool type and avoid the casting.
I finally found the solution :
import UIKit
class ViewController: UIViewController {
var defaults = NSUserDefaults.standardUserDefaults()
#IBOutlet weak var startSecondLevelButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.checkLevelsStatuses()
}
func checkLevelsStatuses() {
startSecondLevelButton.enabled = false
if let lvlWon1 = defaults.objectForKey("lvlWon1") as? Bool {
// if true - level finished
if (lvlWon1) {
startSecondLevelButton.enabled = true
}
}else {
defaults.setBool(false, forKey: "lvlWon1")
}
if let lvlWon2 = defaults.objectForKey("lvlWon2") as? Bool {
} else {
defaults.setBool(false, forKey: "lvlWon2")
}
}
that was because the viewDidLoad was wrong.

Using Swift to display title of currently playing .MP3

I was wondering if there was a straight forward way of displaying the image and title of the currently playing MP3 file my music player is playing. My code is as follows and is very simple for this example. I am only wanting to test using one .MP3 that I've included in my project.
class ViewController: UIViewController {
let audioPath:NSURL! = NSBundle.mainBundle().URLForResource("SippinOnFire", withExtension: "mp3")
#IBOutlet var sliderValue: UISlider!
var player:AVAudioPlayer = AVAudioPlayer()
#IBAction func play(sender: AnyObject) {
player.play()
//println("Playing \(audioPath)")
}
#IBAction func pause(sender: AnyObject) {
player.pause()
}
#IBAction func stop(sender: AnyObject) {
player.stop()
player.currentTime = 0;
}
#IBAction func sliderChanged(sender: AnyObject) {
player.volume = sliderValue.value
}
override func viewDidLoad() {
super.viewDidLoad()
var error:NSError? = nil
player = AVAudioPlayer(contentsOfURL: audioPath!, error: &error)
player.volume = 0.5;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
So far I am able to println the full path to the MP3 file but have not been able to use the display the image that is showing as the cover art for my MP3 in the project or to display only the title of the track playing. Could someone help me out with this?
you need to add the import statement for Media player and set the
General Media Item Property Keys
for nowPlayingInfo property. For the MPMediaItemPropertyArtwork you need to take a look at this MPMediaItemArtwork
import MediaPlayer
let audioInfo = MPNowPlayingInfoCenter.defaultCenter()
let audioName = audioPath.lastPathComponent!.stringByDeletingPathExtension
audioInfo.nowPlayingInfo = [ MPMediaItemPropertyTitle: audioName, MPMediaItemPropertyArtist:"artistName"]
To extract the metadata from your mp3 you need to create an AVPlayerItem and access its asset commonMetadata property
let playerItem = AVPlayerItem(URL: audioPath)
let metadataList = playerItem.asset.commonMetadata as! [AVMetadataItem]
for item in metadataList {
if item.commonKey == "title" {
println("Title = " + item.stringValue)
}
if item.commonKey == "artist" {
println("Artist = " + item.stringValue)
}
}
Note: You will have to invoke beginReceivingRemoteControlEvents() otherwise it will not work on the actual device.
override func viewDidLoad() {
super.viewDidLoad()
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
}
With Leonardo's help I was able to accomplish this using the following code:
#IBAction func play(sender: AnyObject) {
let audioInfo = MPNowPlayingInfoCenter.defaultCenter()
println(audioInfo)
player.play()
//println("Playing \(audioPath)")
let playerItem = AVPlayerItem(URL: audioPath)
let metadataList = playerItem.asset.commonMetadata as! [AVMetadataItem]
for item in metadataList {
if let stringValue = item.value as? String {
println(item.commonKey)
if item.commonKey == "title" {
trackLabel.text = stringValue
}
if item.commonKey == "artist" {
artistLabel.text = stringValue
}
}
}
}
You can selectively pick which commonkeys you would like to use with if statements like these and print the text to the labels like this:
if item.commonKey == "title" {
trackLabel.text = stringValue
}
if item.commonKey == "artist" {
artistLabel.text = stringValue
}
Thank you Leonardo for your assistance!

Resources