Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何立即解除其他警报控制器,并立即提供新的警报控制器_Ios_Swift_Swift3_Uialertcontroller - Fatal编程技术网

Ios 如何立即解除其他警报控制器,并立即提供新的警报控制器

Ios 如何立即解除其他警报控制器,并立即提供新的警报控制器,ios,swift,swift3,uialertcontroller,Ios,Swift,Swift3,Uialertcontroller,我目前遇到的问题是,在解雇另一个警报控制器后,延迟提交新的警报控制器 我的情况如下: 使用MPC的对等连接有两个角色:主和从 理想情况:只有一台主机可用 但是,当设备之间没有连接时,每个设备都可以设置为主设备。 当两个主设备都连接时,理想情况会发生冲突。 因此,我想选举大师。 当两台设备都是单独主控设备时 现在已连接,则主选择的警报控制器将在每个设备中提示。当其中一个设备选项卡先按下“保持为主”按钮时,另一个设备将关闭选举警报控制器并提示“xxx保持为主”警报。 但是,我发现解除之前的警报控制器

我目前遇到的问题是,在解雇另一个警报控制器后,延迟提交新的警报控制器

我的情况如下:

使用MPC的对等连接有两个角色:主和从

理想情况:只有一台主机可用

但是,当设备之间没有连接时,每个设备都可以设置为主设备。

当两个主设备都连接时,理想情况会发生冲突。

因此,我想选举大师。

当两台设备都是单独主控设备时 现在已连接,则主选择的警报控制器将在每个设备中提示。当其中一个设备选项卡先按下“保持为主”按钮时,另一个设备将关闭选举警报控制器并提示“xxx保持为主”警报。
但是,我发现解除之前的警报控制器有延迟

MainVC中的代码:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(testing), name: NSNotification.Name(rawValue: "hasMaster"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(stayAsMaster), name: NSNotification.Name(rawValue: "StayAsMaster"), object: nil)

}

func testing(notification: Notification){
    if(appDelegate.mpcHandler.checkNoOfPeersConnected()>0){
        if self.appDelegate.masterSlaveDataController.checkHasMaster() && self.appDelegate.masterSlaveDataController.checkMaster(){
            self.promptHasMaster()
        }
        else{
            DispatchQueue.main.asyncAfter(deadline: .now()){
                if self.appDelegate.masterSlaveDataController.checkHasMaster() && self.appDelegate.masterSlaveDataController.checkMaster(){
                    self.promptHasMaster()
                }
            }
        }
    }
}

func promptHasMaster(){//prompt Elect Master Alert Controller
    let alertController = UIAlertController(title: "Elect Master", message: "There are more than one masters in the connection. One of you has to give up the master role and switch to slave!", preferredStyle: .alert)
    let peerID = self.appDelegate.mpcHandler.session.myPeerID
    let m = UIAlertAction(title: "Stay as Master", style: .default, handler: { (alert) in
        self.appDelegate.mpcHandler.send(d: self.mToDictionary(peerID: peerID, action: "stayAsMaster")!)
        })
    let s = UIAlertAction(title: "Switch to Slave", style: .default, handler: { (alert) in
        self.appDelegate.mpcHandler.send(d: self.mToDictionary(peerID: peerID, action: "switchToSlave")!)
        })
    alertController.addAction(m)
    alertController.addAction(s)
    self.present(alertController, animated: true, completion: nil)

}

//Create NSDictionary for sending peerID
func mToDictionary(peerID: MCPeerID, action: String) -> [NSDictionary]?{
    var dict: [NSDictionary] = [["action" : action]]
    let d = ["peerID" : peerID] as NSDictionary
    dict.append(d)
    return dict
}

func stayAsMaster(notification: Notification){
    let peerId = NSDictionary(dictionary: notification.userInfo!)
    print("stay as master", peerId.allValues)
    if presentedViewController == nil {
        let alertController = UIAlertController(title:  String(describing: peerId.allValues) + " remains as Master", message: "", preferredStyle: .alert)
        let dismiss = UIAlertAction(title: "Dismiss", style: .destructive, handler: nil)
        alertController.addAction(dismiss)
        self.present(alertController, animated: true, completion: nil)
    } else{
        let alertController = UIAlertController(title:  String(describing: peerId.allValues) + " remains as Master", message: "", preferredStyle: .alert)
        let dismiss = UIAlertAction(title: "Dismiss", style: .destructive, handler: nil)
        alertController.addAction(dismiss)
        self.dismiss(animated: false) { () -> Void in
            self.present(alertController, animated: true, completion: nil)

        }
    }

}
钱德勒的代码:

func send(d: [NSDictionary]){
    NSLog("%@", "Send data: \(d) to \(session.connectedPeers.count) peers")

    if session.connectedPeers.count > 0{
        do {
            let data = NSKeyedArchiver.archivedData(withRootObject: d)
            try self.session.send(data, toPeers: session.connectedPeers, with: .reliable)
        } catch {
            NSLog("%@", "Error for sending data: \(error)")
        }
    }
}

func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
    NSLog("%@", "didReceive: \(data)")
    if var dict: [NSDictionary] = NSKeyedUnarchiver.unarchiveObject(with: data) as? [NSDictionary]{
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let d = dict.removeFirst()
        switch d.value(forKey: "action") as! String {
        case "stayAsMaster":
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "StayAsMaster"), object: nil, userInfo: [peerID:dict.first!])
        default: break
        }
    }
}

当我在一台设备的警报控制器中标记“保持为主”时,另一台设备的Xcode控制台立即打印
打印(“保持为主”,peerId.allValues)
,但几秒钟后它会解除当前警报控制器

请问有人知道吗?感谢您提前提供的帮助。

我发现您的代码中存在一些潜在问题,请尝试更改这些问题:

  • 无论何时发布通知,请将此类代码包装在
    DispatchQueue.main.async

    DispatchQueue.main.async {
      NotificationCenter.default.post(name: NSNotification.Name(rawValue: "StayAsMaster"), object: nil, userInfo: [peerID:dict.first!])
    }
    
    请检查这里:

  • 请添加
    removeObserver
    (或者您可能在
    deinit
    后崩溃):


我尝试了你的建议,但仍然存在延迟问题。无论如何,谢谢你的帮助。谢谢你的帮助!当我在MPCHandler中添加'DispatchQueue.main.async{NotificationCenter.default.post(名称:NSNotification.name(rawValue:“StayAsMaster”)、对象:nil、用户信息:[peerID:dict.first!]}时,它就起作用了。但是,我不确定在哪里添加“deinit{NotificationCenter.default.removeObserver(self)}”。您能给我一些gif图像吗?
deinit {
  NotificationCenter.default.removeObserver(self)
}