每次歌曲改变时,我都会尝试将歌曲标题和艺术家添加到数据库中。该程序目前正在这样做,但出于某种原因,当我转到下一首歌曲时,同一首歌曲在数据库中被多次添加,即歌曲1在解析时被添加了6次。为什么会发生这种情况?我该如何解决?
func applicationDidEnterBackground(application: UIApplication) {
print("entered background")
NSNotificationCenter.defaultCenter().addObserver(self, selector: "getNowPlayingItem", name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: nil)
musicPlayer.beginGeneratingPlaybackNotifications()
backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({ () -> Void in
UIApplication.sharedApplication().endBackgroundTask(self.backgroundTask!)
self.backgroundTask = UIBackgroundTaskInvalid
})
}
func getNowPlayingItem() {
if let nowPlaying = musicPlayer.nowPlayingItem {
let title = nowPlaying[MPMediaItemPropertyTitle]
let artisttest = nowPlaying[MPMediaItemPropertyTitle]
if let artist = nowPlaying[MPMediaItemPropertyArtist] {
let objectPointer = PFObject(className: "Pointer")
let object = PFObject(className: "MasterSongs")
let query = PFQuery(className: "Pointer")
query.findObjectsInBackgroundWithBlock({
(objects: [AnyObject]?, error: NSError?) -> Void in
var objectIDs = objects as! [PFObject]
for i in 0...objectIDs.count-1{
self.Parsearray.append((objectIDs[i].valueForKey("title") as? String)!)
}
if self.Parsearray.contains(title! as! String){
print("already in db")
}else{
objectPointer["title"] = title
objectPointer["user"] = PFUser.currentUser()
objectPointer["artist"] = artist
objectPointer.saveInBackground()
//parseClass.saveInBackgroundWithBlock{(success: Bool, error: NSError!) -> Void in
objectPointer.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if success == false {
print(error)
} else {
print("Posted succesfully")
}
})
}
})
}
if(artisttest == nil){
let objectPointer = PFObject(className: "Pointer")
let query = PFQuery(className: "Pointer")
query.findObjectsInBackgroundWithBlock({
(objects: [AnyObject]?, error: NSError?) -> Void in
var objectIDs = objects as! [PFObject]
for i in 0...objectIDs.count-1{
self.Parsearray.append((objectIDs[i].valueForKey("title") as? String)!)
}
if self.Parsearray.contains(title! as! String){
print("already in db")
}else{
objectPointer["title"] = title
objectPointer["user"] = PFUser.currentUser()
objectPointer["artist"] = "No artist found :("
objectPointer.saveInBackground()
}
})
}
}
}
func applicationWillEnterForeground(application: UIApplication) {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
答案 0 :(得分:0)
我注意到的一件事是,每次调用MPMusicPlayerControllerNowPlayingItemDidChangeNotification
时都会为applicationDidEnterBackground
添加一个观察者。
你没有包含applicationDidEnterForeground
功能 - 但希望你在那里删除那些观察者。如果您不删除观察者,则会导致为每个getNowPlayingItem
调用applicationDidEnterBackground
选择器。所以6 applicationDidEnterBackground
= 6 getNowPlayingItem
。