我試圖在歌曲每次改變時將歌曲標題和藝術家添加到數據庫中。該節目目前是這樣做的,但由於某種原因,當我進入下一首歌曲時,同一首歌曲會在數據庫中多次添加,即歌曲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)
}
我的猜測:你每次添加將調用'getNowPlayingItem'的觀察者,但你不會刪除它。所以當'applicationDidBecomeActive:'移除觀察者時。 – Larme
哈哈,你打敗我吧! –