iOS-Swift XMPP 获取好友、上线、及消息等方法

2016-12-30 02:39

一、XMPPStreamDelegate 协议

上线下线

   // 上线
   private func goOnline() -> Void {
        // 生成状态元素
        let presence: XMPPPresence = XMPPPresence(type: "available")
        self.xmppStream!.send(presence)
    }
    // 下线
    private func goOffline() -> Void {
        let presence: XMPPPresence = XMPPPresence(type: "unavailable")
        self.xmppStream!.send(presence)
    }
 // 断开连接成功
   func xmppStreamDidDisconnect(_ sender: XMPPStream, withError error: Error?) -> Void {     
    }
// 连接超时
    func xmppStreamConnectDidTimeout(_ sender: XMPPStream) -> Void {
    }
// 连接服务器
    func xmppStreamDidConnect(_ sender: XMPPStream) -> Void {
}
 // 验证通过
    func xmppStreamDidAuthenticate(_ sender: XMPPStream) -> Void {
}
  // 验证不通过
    func xmppStream(_ sender: XMPPStream, didNotAuthenticate error: NSXMLElement) -> Void {
}
 // 收到好友状态
    func xmppStream(_ sender: XMPPStream!, didReceive presence: XMPPPresence!) {
        // 取得好友状态
        let presenceType = presence.type()
        // 当前用户
        let userId = sender.myJID.user
        // 在线用户
        let presenceFromUser = presence.from().user
        if (!(presenceFromUser == userId)) {
            // 在线状态
            if presenceType == "available" {
           }  else { // 离线状态
           }
       }
  }
// 收到消息
  func xmppStream(_ sender: XMPPStream, didReceive message:XMPPMessage) -> Void {
}
// 发送消息成功
 func xmppStream(_ sender: XMPPStream!, didSend message: XMPPMessage!) {
}
// 发送消息失败
 func xmppStream(_ sender: XMPPStream!, didFailToSend message: XMPPMessage!, error: 
}

二、XMPPRosterDelegate 协议

获取好友

   func xmppRosterDidBeginPopulating(_ sender: XMPPRoster, withVersion version: String) -> Void {
        // print("开始获取好友 %s,%d", #function, #line)
    }
    func xmppRosterDidEndPopulating(_ sender: XMPPRoster) -> Void {
        // print("获取好友结束 %s,%d", #function, #line)
    }
    // 一次获取一个好友
    func xmppRoster(_ sender: XMPPRoster, didReceiveRosterItem item: DDXMLElement) -> Void {
        // print("获取好友 %s %d", #function, #line)
        // print("好友信息 %@",item);
    }
    func xmppRoster(_ sender: XMPPRoster, didReceiveRosterPush iq: XMPPIQ) -> Void {
}
    func xmppRoster(_ sender: XMPPRoster, didReceivePresenceSubscriptionRequest presence:XMPPPresence) -> Void {
        print("获取好友请求")
}
// 删除好友
    func removeFriendWithFriendName(friendName: String) -> Void {
        let friendJid = XMPPJID(string: friendName)
        self.xmppRoster!.removeUser(friendJid)
    }
    // 添加好友
    func addFriendWithUserId(userId: String?, friendName: String, groupName: String?) {
        let nickName: String? = friendName.isEmpty ? nil : friendName
        let groupArray: Array? = groupName == "我的好友" ? nil : [groupName!]
        let friendJid: XMPPJID = XMPPJID(user: userId, domain: kDomain, resource: "iOS")
        self.xmppRoster!.addUser(friendJid, withNickname: nickName, groups: groupArray, subscribeToPresence: true)
    }
PS: 有什么疑问欢迎留言。