iOS Firebase排序和限制 - 未调用观察者

时间:2016-10-11 00:38:45

标签: ios swift firebase firebase-realtime-database

这是我的数据模型。

project-foo
 -posts
   -KLs123412341234
     key: "-KLs123412341234"
     message: "free cupcakes"
     time: 1467675688163
   -...
     key: "..."
     message: "..."
     time: ...

我想在过去15分钟内只收到帖子。 我在我的Firebase控制台中看到要添加的孩子,但问题是观察者似乎没有被调用 - "hello"没有被打印。

我的iOS应用程序具有以下代码,被调用:

class ViewController: UIViewController {

    var ref: FIRDatabaseReference?

    override func viewDidLoad() {
        super.viewDidLoad()

        ref = FIRDatabase.database().reference()
        ref!.queryOrderedByChild("time")
            .queryStartingAtValue(startTime())
            .observeEventType(.ChildAdded, withBlock: { snapshot in
            print("hello")
        })

    }
}

我的Android应用程序具有以下代码,确实被调用:

Query query = mDatabase.orderByChild("time").startAt((double)startTime());
query.addChildEventListener(new PostListener(this, mMap));

class PostListener implements ChildEventListener {
    public PostListener(Context context, GoogleMap map) {
        ...
    }

    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        Log.i(TAG, "hello");
        ...
    }
}

更新: 我的错误是没有意识到我已使用路径mDatabase初始化posts(在Android版本中)。该修复只是使用ref而非FIRDatabase.database().referenceWithPath("posts")初始化FIRDatabase.database().reference()

1 个答案:

答案 0 :(得分:1)

对于JSON结构,: -

"posts" : {
  "autoID1" : {
    "key" : "autoID1",
    "timestamp" : 101
  },
  "autoID2" : {
    "key" : "autoID2",
    "timestamp" : 102
  },
  "autoID3" : {
    "key" : "autoID3",
    "timestamp" : 103
  },
  "autoID4" : {
    "key" : "autoID4",
    "timestamp" : 104
  },
  "autoID5" : {
    "key" : "autoID5",
    "timestamp" : 105
  },
  "autoID6" : {
    "key" : "autoID6",
    "timestamp" : 106
  },
  "autoID7" : {
    "key" : "autoID7",
    "timestamp" : 107
  }
}

使用此代码: -

  FIRDatabase.database().reference().child("posts").queryOrderedByChild( "timestamp").queryStartingAtValue(101).queryEndingAtValue(103).observeEvenType(.Value, with: { (snap) in
        if let snapDict = snap.value as? [String:AnyObject]{

            for each in snapDict{

                print(each.value)

            }
          }
        }, withCancel: {(err) in


    })

确保您的安全规则允许用户检索posts

使用 .ChildAdded 仅在将子节点添加到该数据库节点时才会被调用。使用 .Value 将检索整个数据,其时间戳介于这些值之间

现在很可能无法从 FIRServerValue.timestamp() 获取Timestamp值,因为它只是发送到firebase服务器的命令,用于在该特定节点添加时间戳。

因此,请使用自定义时间戳来存储时间戳,并为最终值添加15分钟到该时间戳。

阅读此Manipulate NSDate