分页直到结束

时间:2018-08-05 15:02:47

标签: ios swift pubnub

我有一个使用PubNub作为聊天服务的应用。登录后,我想下载所有历史消息。不幸的是,PubNub将邮件的最大数量限制为100,因此您必须使用分页下载所有邮件,直到没有更多邮件到达为止。 我要实现的工作流程如下:

  1. 加载前100条消息
  2. 处理它们(存储在应用程序中)
  3. 加载接下来的100条消息
  4. 依此类推。

他们提供的方法如下:

client.historyForChannel(channel, start: nil, end: nil, includeTimeToken: false)
{ (result, status) in
      // my code here...
}

问题是,在“我的代码在这里...”部分中,我需要再次调用该函数(使用startDate)以加载接下来的100条消息。但是要再次调用该函数,我需要设置一个完成块,该完成块与调用该函数的完成块完全相同。这是一个无限循环。.我该如何解决呢?非常感谢你!

1 个答案:

答案 0 :(得分:1)

PubNub历史分页示例代码

所有SDK都有用于实现历史分页的示例代码。请参阅PubNub Swift SDK Storage API Reference History Paging section

以下是内联代码:

分页历史记录响应: 您可以通过传递0或有效的时间标记作为参数来调用该方法。

// Pull out all messages newer then message sent at 14395051270438477.
let date = NSNumber(value: (14395051270438477 as CUnsignedLongLong));
self.historyNewerThen(date, onChannel: "history_channel", withCompletion:  { (messages) in

    print("Messages from history: \(messages)")
})


func historyNewerThen(_ date: NSNumber, onChannel channel: String, 
                      withCompletion closure: @escaping (Array<Any>) -> Void) {

    var msgs: Array<Any> = []
    self.historyNewerThen(date, onChannel: channel, withProgress: { (messages) in

        msgs.append(contentsOf: messages)
        if messages.count < 100 { closure(msgs) }
    })
}

private func historyNewerThen(_ date: NSNumber, onChannel channel: String, 
                              withProgress closure: @escaping (Array<Any>) -> Void) {

    self.client?.historyForChannel(channel, start: date, end: nil, limit: 100, 
                                   reverse: false, withCompletion: { (result, status) in

        if status == nil {

            closure((result?.data.messages)!)
            if result?.data.messages.count == 100 {

                self.historyNewerThen((result?.data.end)!, onChannel: channel, 
                                      withProgress: closure)
            }
        }
        else {

            /**
             Handle message history download error. Check 'category' property
             to find out possible reason because of which request did fail.
             Review 'errorData' property (which has PNErrorData data type) of status
             object to get additional information about issue.

             Request can be resent using: [status retry];
             */
        }
    })
}

请参阅其他SDK语言特定实现中的同一部分。