Quickblox:如何确定用户是否在线?

时间:2013-07-31 05:53:47

标签: quickblox

有没有办法找出Quickblox用户是否在线? 我正在使用Quickblox iOS SDK。

2 个答案:

答案 0 :(得分:4)

答案 1 :(得分:1)

  

迅速5:

要获取对手用户的在线状态和准确的最后一次,我们必须使用addUserToContactListRequest() API将这两个用户添加到彼此的contactList中。


用户A 发送请求与用户B 成为“朋友”。用户B接受好友请求。现在,用户A和B出现在彼此的名单中。


步骤1:

检查对手用户是否已经添加到联系人中

 let isAvailable = QBChat.instance.contactList?.contacts?.filter {(contacts) -> Bool in

    // self.dialog.recipientID is an opponent user's ID 

    return contacts.userID == self.dialog.recipientID ? true : false
}

如果在联系人中可用,请检查联机状态,如果不可用,则发送请求以添加联系人。

    if isAvailable!.count > 0 {
         if isAvailable![0].isOnline {
            //print("User Is Online")
         } else {
            //print("User Is Offline")
            //Check Last Seen
            self.fetchLastSeen(userId: self.dialog.recipientID)
         }
    } else {
           QBChat.instance.addUser(toContactListRequest: UInt(self.dialog!.recipientID)) { (err) in
                    print("\(err)")
                }
  }

第2步:

实现QBChatDelegate方法。

添加联系人请求

// This method will get called whenever you will receive any new add contact request
    func chatDidReceiveContactAddRequest(fromUser userID: UInt) {
        //Confirm add to contact list request.    
        QBChat.instance.confirmAddContactRequest(userID) { (error) in
        }
    }

如果联系人列表中的用户的在线状态已更改,则调用以下方法。

func chatDidReceiveContactItemActivity(_ userID: UInt, isOnline: Bool, status: String?) {
    if userID == self.dialog.recipientID {
        if isOnline {
            print("User Is Online")
         } else {
            //print("User Is Offline")
            //Check Last Seen
            fetchLastSeen(userId: NSInteger(userID)) 
        }
    }
}

步骤3:

使用此lastActivityForUser()

获取用户的最后一次查看
func fetchLastSeen(userId: NSInteger){
    QBChat.instance.lastActivityForUser(withID: UInt(userId)) { (timeStamp, err) in
        print(timeStamp)
       // here we get total seconds, since how long user was inactive 
       // minus the seconds from current time 
        if err == nil {
            let updatedTime = Calendar.current.date(byAdding: .second, value: -Int(timeStamp), to: Date())

            guard let dateSent = updatedTime else {
                return
            }

            var lastSeenStr = ""
            if (Calendar.current.isDateInToday(updatedTime!)){
                lastSeenStr = "Today"
            } else if (Calendar.current.isDateInYesterday(updatedTime!)){
                lastSeenStr = "Yesterday"
            } else {
                let dateFormat = DateFormatter()
                dateFormat.dateFormat = "d-MMM"
                lastSeenStr = dateFormat.string(from: updatedTime!)
            }

            let text = messageTimeDateFormatter.string(from: dateSent)
            print("\(lastSeenStr + " " + text)") // e.g. 11-Sep 11:44 AM
        }
    }
}