美文网首页
iOS MultipeerConnectivity.framew

iOS MultipeerConnectivity.framew

作者: iOS虞 | 来源:发表于2021-05-08 14:46 被阅读0次
    1. 概述 MultipeerConnectivity.framework iOS 7.0苹果新增的,通过附近Wi-Fi网络P2P蓝牙传输数据(类似于苹果的隔空投送)官方文档
    image.png
    1. Xcode -> TARGETS ->info 添加Bonjour services, Item0 = _yzk._tcp 格式说明

    2. 直接上代码

    import UIKit
    import MultipeerConnectivity
    
    class ViewController: UIViewController {
    
        // 创建PeerID
        lazy var peerid: MCPeerID = {
            let peer = MCPeerID(displayName: UIDevice.current.name)
            return peer
        }()
        
        // 创建session
        lazy var session: MCSession = {
            let ss = MCSession(peer: peerid, securityIdentity: nil, encryptionPreference: .required)
            ss.delegate = self
            return ss
        }()
        
        
        // 创建广播AdvertiserAssistant
        lazy var advertiser: MCAdvertiserAssistant = {
            let advertiser = MCAdvertiserAssistant(serviceType: "yzk", discoveryInfo: nil, session: session)
            advertiser.delegate = self
            return advertiser
        }()
        
        // 搜索PeerID
        lazy var browserVC: MCBrowserViewController = {
            let browser = MCBrowserViewController(serviceType: "yzk", session: session)
            browser.delegate = self
            return browser
        }()
        
        
        
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
            
            let button = UIButton(frame: CGRect(x: 10, y: 100, width: self.view.frame.width - 20, height: 44))
            button.setTitle("开启广播", for: .normal)
            button.backgroundColor = UIColor.red
            button.addTarget(self, action: #selector(openClick), for: .touchUpInside)
            self.view.addSubview(button)
            
            
            let button2 = UIButton(frame: CGRect(x: 10, y: button.frame.maxY + 30, width: self.view.frame.width - 20, height: 44))
            button2.setTitle("搜索", for: .normal)
            button2.backgroundColor = UIColor.green
            button2.addTarget(self, action: #selector(scanClick), for: .touchUpInside)
            self.view.addSubview(button2)
            
        }
    
        
        @objc func openClick() {
            
            advertiser.start()
            
        }
        
        @objc func scanClick() {
        
            self.present(browserVC, animated: true, completion: nil)
            
        }
        
        
        deinit {
            print("释放了")
        }
    }
    
    
    // MARK: MCSessionDelegate
    extension ViewController: MCSessionDelegate {
        
        // MARK: 接收完成
        func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {
            
            print("接收完成")
        }
        
        func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
            
            switch state {
            case .notConnected:
                print("未连接")
            case .connecting:
                print("正在连接中")
            case .connected:
                print("连接成功")
            default:
                print("")
            }
        }
        
        func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
            
        }
        
        func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
            
        }
        
        func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {
            
        }
        
        // 这个是可选的
        func session(_ session: MCSession, didReceiveCertificate certificate: [Any]?, fromPeer peerID: MCPeerID, certificateHandler: @escaping (Bool) -> Void) {
            
            certificateHandler(true)
        }
        
    }
    
    // MARK: MCAdvertiserAssistantDelegate
    extension ViewController: MCAdvertiserAssistantDelegate {
        
        func advertiserAssistantWillPresentInvitation(_ advertiserAssistant: MCAdvertiserAssistant) {
    
        }
    
    
        func advertiserAssistantDidDismissInvitation(_ advertiserAssistant: MCAdvertiserAssistant) {
    
        }
        
    }
    
    
    extension ViewController: MCBrowserViewControllerDelegate {
        
        func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
            
            browserViewController.dismiss(animated: true, completion: nil)
        }
        
        func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
    
            browserViewController.dismiss(animated: true, completion: nil)
        }
    }
    
    1. 遇到的坑
      点击搜索到的设备一直Connecting中一直连接不上,在AppDelegate中去掉UISceneSession相关代码后被连接的设备上就会弹出是否接受的弹框点击接受就连接上了,感觉是苹果的BUG

    相关文章

      网友评论

          本文标题:iOS MultipeerConnectivity.framew

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