ios – Firebase删除观察者

前端之家收集整理的这篇文章主要介绍了ios – Firebase删除观察者前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在代码删除Firebase观察者时遇到问题.这是结构的细分:
var ref = Firebase(url:"https://MY-APP.firebaseio.com/")
var handle = UInt?

override func viewDidLoad() {
    handle = ref.observeEventType(.ChildChanged,withBlock: {
        snapshot in

        //Do something with the data
    }
}

override func viewWillDisappear(animated: Bool) {
    if handle != nil {
        println("Removed the handle")
        ref.removeObserverWithHandle(handle!)
    }
}

现在,当我离开viewcontroller时,我看到“Removed the handle”被打印出来,但是当我返回viewcontroller时,我的观察者会为每个事件调用两次.当我离开并再次返回时,它被召唤三次.等等.为什么观察者没有被移除?

我也在代码中稍后调用ref.setValue(“some value”),这可能与它有什么关系吗?

解决方法

以为我有这个错误,但实际上我试图删除观察者的错误参考.

原始代码

let ref: FIRDatabaseReference = FIRDatabase.database().reference()
var childAddedHandles: [String:FIRDatabaseHandle] = [:]

func observeFeedbackForUser(userId: String) {
    if childAddedHandles[userId] == nil { // Check if observer already exists

        // NOTE: - Error is caused because I add .child(userId) to my reference and
        //     do not when I call to remove the observer.

        childAddedHandles[userId] = ref.child(userId).observeEventType(.ChildAdded) { 
            [weak self] (snapshot: FIRDataSnapshot) in

            if let post = snapshot.value as? [String:AnyObject],let likes = post["likes"] as? Int where likes > 0 {             

                self?.receivedFeedback(snapshot.key,forUserId: userId)          
            }
        }
    }
}

func stopObservingUser(userId: String) {
    // THIS DOES NOT WORK

    guard let cah = childAddedHandles.removeValueForKey(userId) else {
        print("Not observing user")
        return
    }

    // Error! I did not add .child(userId) to my reference
    ref.removeObserverWithHandle(cah)
}

固定代码

func stopObservingUser(userId: String) {
    // THIS WORKS

    guard let cah = childAddedHandles.removeValueForKey(userId) else {
        print("Not observing user")
        return
    }

    // Add .child(userId) here
    ref.child(userId).removeObserverWithHandle(cah)
}
原文链接:https://www.f2er.com/iOS/333223.html

猜你在找的iOS相关文章