为什么标题会重复? [英] Why is the title being repeated?

查看:114
本文介绍了为什么标题会重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在播放当前播放的歌曲,并捕获标题和艺术家,并将其存储在解析中。出于某种原因,当歌曲播放时,该节目增加4个相同的标题/艺术家。我反而只想要一个。我该如何解决这个问题?

I am getting the current playing song, and capturing the title and artist, and storing it in parse. For some reason, when the song plays, the program adds 4 or so of the same title/artist. I instead just want one. How do I fix this?

我的对象如解析数据浏览器所示

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated);

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "getNowPlayingItem", name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: nil)
    musicPlayer.beginGeneratingPlaybackNotifications()
}

func getNowPlayingItem() {

    NSNotificationCenter.defaultCenter().removeObserver(self)

    if  let nowPlaying = musicPlayer.nowPlayingItem  {
        let title = nowPlaying[MPMediaItemPropertyTitle] as? String
        let artisttest = nowPlaying[MPMediaItemPropertyTitle]
        if let artist = nowPlaying[MPMediaItemPropertyArtist] as? String{
            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)!)
                    // print(self.Parsearray)
                }

                if self.Parsearray.contains(title!){
                    print("already in db")
                }else{
                    objectPointer["title"] = title
                    objectPointer["user"] = PFUser.currentUser()
                    objectPointer["artist"] = artist

                    objectPointer.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
                        if(error != nil){
                            print(error)
                        }else{
                            NSNotificationCenter.defaultCenter().addObserver(self, selector: "getNowPlayingItem", name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: nil)
                        }
                    })
                }
            })
        }else{

            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)!)

                    // print(self.Parsearray)
                }

                if self.Parsearray.contains(title!){
                    print("already in db")
                }else{
                    objectPointer["title"] = title
                    objectPointer["user"] = PFUser.currentUser()
                    objectPointer["artist"] = "No artist found :("

                    objectPointer.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in

                        if(error != nil){
                            print(error)
                        }else{
                            NSNotificationCenter.defaultCenter().addObserver(self, selector: "getNowPlayingItem", name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: nil)
                        }
                    })
                }
            })
        }
    }
}


推荐答案

根据证据,该函数很有可能 getNowPlayingItem 被快速调用几次。它会启动查询,其中一小部分在保存任何内容之前完成。那些查询完成(尚未完成保存)启动少量保存并获得少量对象。

From the evidence, there's a good chance that the function getNowPlayingItem is being called several times rapidly. It launches queries, a handful of which complete before anything is saved. Those query completions (with no saves done yet) launch a handful of saves and you get a handful of objects.

通过在方法开头打印消息来检查并且在 saveInBackground 之前注意控制台上的时间戳。

Check this by printing a message at the start of the method and just before saveInBackground paying attention to the timestamps on the console.

如果我是对的,那么解决方法是simple:(a)找出为什么方法被调用了很多次并修复它,或者(b)将一个布尔实例变量添加到封闭类中,称之为 busySaving 。在方法开始时,如果 busySaving 为真,则纾困,否则将其设置为真随身携带。将 saveInBackground()更改为 saveInBackgroundWithBlock()并重置 busySaving 完成块中的标记。

If I'm right, the fix is simple: (a) find out why the method is being called so many times and fix that, or (b) add a boolean instance variable to the enclosing class, call it something like busySaving. At the start of the method, bail out if busySaving is true, otherwise set it to true an carry on. Change your saveInBackground() to saveInBackgroundWithBlock() and reset the busySaving flag in the completion block.

编辑
现在我们看到为什么要重复调用它:因为正在收到通知反复。修复的一种方法(上面的想法(a))将是在 getNowPlayingItem 的开头停止观察该通知(NSNotificationCenter removeObserver)。然后,由于您希望获得后续通知,请在保存后使用 saveInBackgroundWithBlock 重新添加自己作为观察者。请注意,这与 saveInBackground 请参阅此处以供参考

EDIT Now we see why it's being called repeatedly: because the notification is being received repeatedly. One way to fix (idea (a) above) would be to stop observing that notification (NSNotificationCenter removeObserver) at the start of getNowPlayingItem. Then, since you want to get subsequent notifications, re-add yourself as an observer after the save, using saveInBackgroundWithBlock. Notice this is different from saveInBackground see here for reference.

如果您愿意,上述构思(b)也适用。

Idea (b) above still applies as well, if you prefer.

这篇关于为什么标题会重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆