代码之家  ›  专栏  ›  技术社区  ›  Stephan Boner

分页到结尾

  •  1
  • Stephan Boner  · 技术社区  · 6 年前

    我有一个应用程序正在使用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 回复  |  直到 6 年前
        1
  •  1
  •   Craig Conover sandeep nag    6 年前

    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];
                 */
            }
        })
    }
    

    请参阅其他特定于SDKs语言的实现中的同一节。