美文网首页
iOS开发XMPPFramework使用swift

iOS开发XMPPFramework使用swift

作者: 小鬼别多嘴 | 来源:发表于2019-11-07 10:53 被阅读0次
    import Foundation
    import XMPPFramework
    
    enum connenctToServerState {
        ///登录状态
        case connenctToServerStateLogin
        ///注册状态
        case connenctToServerStateRegister
    }
    
    class XmppManager: NSObject {
        ///管道
        var xmppStream: XMPPStream!
        ///花名册
        var xmppRoster: XMPPRoster!
        ///获取上下文
        var managedObjectContext: NSManagedObjectContext!
        ///获取聊天消息内容
        var messageArchiving: XMPPMessageArchiving!
        ///密码
        var password: String!
        ///连接服务器状态
        var connentToServerState: connenctToServerState!
        ///重连类
        var xmppReconnect: XMPPReconnect!
        ///播放器
        var player: AVAudioPlayer!
        
        static let sharedInstance: XmppManager = {
            let instance = XmppManager()
            return instance
        }()
        
        override init() {
            super.init()
            //初始化通道
            xmppStream = XMPPStream()
            //通信指定ip
            xmppStream.hostName = HostName
            //添加代理
            xmppStream.addDelegate(self, delegateQueue: DispatchQueue.main)
            
            //初始化花名册
            let rosterCoreDataStorage = XMPPRosterCoreDataStorage.sharedInstance()
            xmppRoster = XMPPRoster(rosterStorage: rosterCoreDataStorage!, dispatchQueue: DispatchQueue.global())
            //添加代理
            xmppRoster.addDelegate(self, delegateQueue: DispatchQueue.main)
            //通过管道激活花名册
            xmppRoster.activate(xmppStream)
            
            //初始化聊天对象
            let messageArchivingCoreDataStorage = XMPPMessageArchivingCoreDataStorage.sharedInstance()
            self.messageArchiving = XMPPMessageArchiving(messageArchivingStorage: messageArchivingCoreDataStorage!, dispatchQueue: DispatchQueue.main)
            
            //获取聊天上下文
            self.managedObjectContext = messageArchivingCoreDataStorage?.mainThreadManagedObjectContext
            self.messageArchiving.activate(xmppStream)
            
            //初始化重连类
            self.xmppReconnect = XMPPReconnect()
            self.xmppReconnect.addDelegate(self, delegateQueue: DispatchQueue.main)
        
        }
        
        ///注册
        func registerWithUserName(_ userName: String,password: String) {
            self.password = password
            connentToServerState = .connenctToServerStateRegister
            connentToServerToUserName(userName)
        }
        
        ///登录
        func loginWithUserName(_ userName: String,password: String) {
            self.password = password
            self.connentToServerState = .connenctToServerStateLogin
            connentToServerToUserName(userName)
        }
        
        ///创建账号链接服务器
        func connentToServerToUserName(_ userName: String) {
            let jid = XMPPJID(user: userName, domain: Domain, resource: resource)
            xmppStream.myJID = jid
            connentToServer()
        }
        
        ///链接服务器
        func connentToServer() {
            if xmppStream.isConnected {
                disConnectToServer()
            }
            
            do {
                try XmppManager.sharedInstance.xmppStream.connect(withTimeout: 5)
            } catch let error {
                print(error)
            }
        }
        
        ///断开服务器
        func disConnectToServer() {
            //生成网络状态
            let presence = XMPPPresence(type: "unavailable")
            //改变通道状态
            xmppStream.send(presence)
            //断开连接
            xmppStream.disconnect()
        }
        
        ///播放音频
        func play() {
            let path = Bundle.main.path(forResource: "in", ofType: "caf")
            do {
                let player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path!))
                player.play()
            } catch let error {
                print(error)
            }
        }
    }
    
    extension XmppManager: XMPPStreamDelegate {
        func xmppStreamDidDisconnect(_ sender: XMPPStream, withError error: Error?) {
            print("已断开连接")
        }
        
        func xmppStream(_ sender: XMPPStream, didNotAuthenticate error: DDXMLElement) {
            print("登录失败")
        }
        
        func xmppStream(_ sender: XMPPStream, didNotRegister error: DDXMLElement) {
            print("注册失败")
        }
        
        func xmppStreamDidAuthenticate(_ sender: XMPPStream) {
            print("登录成功")
            let presence = XMPPPresence(type: "available")
            xmppStream.send(presence)
        }
        
        func xmppStreamDidConnect(_ sender: XMPPStream) {
            print("连接成功")
            switch connentToServerState {
            case .connenctToServerStateLogin:
                do {
                    try sender.authenticate(withPassword: self.password)
                } catch let error {
                    print(error)
                }
            case .connenctToServerStateRegister:
                do {
                try sender.register(withPassword: password)
                } catch let error {
                print(error)
                }
            default:
                print("default")
            }
        }
        
        func xmppStream(_ sender: XMPPStream, didReceive message: XMPPMessage) {
            let text = message.body
            if text != nil {
                print(text!)
                let path = Bundle.main.path(forResource: "in", ofType: "caf")
                let soundUrl = URL(fileURLWithPath: path!)
                do {
                    NotificationCenter.default.post(name: Notification.Name(rawValue: "654321"), object: nil)
                    XmppManager.sharedInstance.player = try AVAudioPlayer(contentsOf: soundUrl)
                    XmppManager.sharedInstance.player.volume = 1.0
                    XmppManager.sharedInstance.player.play()
                } catch let error {
                    print(error)
                }
            }else {
                NotificationCenter.default.post(name: Notification.Name(rawValue: "123456"), object: nil)
            }
        }
    }
    
    extension XmppManager: XMPPRosterDelegate {
        
        func xmppRosterDidBeginPopulating(_ sender: XMPPRoster, withVersion version: String) {
            print("开始获取好友")
        }
        
        func xmppRosterDidEndPopulating(_ sender: XMPPRoster) {
            print("获取还有结束")
        }
        
        func xmppRoster(_ sender: XMPPRoster, didReceiveRosterItem item: DDXMLElement) {
            print("获取到好友\(item)")
        }
        
        func xmppRoster(_ sender: XMPPRoster, didReceivePresenceSubscriptionRequest presence: XMPPPresence) {
            let alertVC = UIAlertController(title: "\(String(describing: presence.from?.bare))想添加你为好友", message: "", preferredStyle: .alert)
            let acceptAction = UIAlertAction(title: "接受", style: .default) { (action) in
                self.xmppRoster.acceptPresenceSubscriptionRequest(from: presence.from!, andAddToRoster: true)
            }
            alertVC.addAction(acceptAction)
            let cancelAction = UIAlertAction(title: "拒绝", style: .cancel) { (action) in
                self.xmppRoster.rejectPresenceSubscriptionRequest(from: presence.from!)
            }
            alertVC.addAction(cancelAction)
            Login.getCurrentVC().present(alertVC, animated: true, completion: nil)
        }
        
    }
    
    extension XmppManager: XMPPReconnectDelegate {
        func xmppReconnect(_ sender: XMPPReconnect, didDetectAccidentalDisconnect connectionFlags: SCNetworkConnectionFlags) {
            print("意外断开连接")
            if Profile.ofUserName != "" && Profile.ofPasswd != "" {
                XmppManager.sharedInstance.loginWithUserName(Profile.ofUserName!, password: Profile.ofPasswd!)
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:iOS开发XMPPFramework使用swift

          本文链接:https://www.haomeiwen.com/subject/yfbmbctx.html