简体   繁体   English

Swift 等待另一个视图控制器的任务完成

[英]Swift wait task finish from another viewcontroller

I have a Viewcontroller VC_B where I connect to Wifi by using "NEHotspotConfigurationManager.shared" to a special device.我有一个 Viewcontroller VC_B,我通过使用“NEHotspotConfigurationManager.shared”连接到 Wifi 到一个特殊设备。 This function currently errors because it will return nil whenever success or failure.这个 function 当前错误,因为无论成功或失败它都会返回 nil。 Please follow these links below.请点击以下链接。 https://developer.apple.com/forums/thread/109412 https://stackoverflow.com/.../nehotspotconfigurationmanag.. . https://developer.apple.com/forums/thread/109412 https://stackoverflow.com/.../nehotspotconfigurationmanag..

So I will create a Viewcontroller VC_A, then use "pathUpdateHandler" to catch events whenever the wifi connection changed.所以我将创建一个 Viewcontroller VC_A,然后在 wifi 连接发生变化时使用“pathUpdateHandler”来捕获事件。 Then save wifi SSID to CURENT_SSID by using CoreLocation.然后使用 CoreLocation 将 wifi SSID 保存到 CURENT_SSID。

  1. access device wifi by DEVICE_SSID at VC_B.通过 VC_B 的 DEVICE_SSID 访问设备 wifi。
  2. wait until CURENT_SSID successfully is updated at VC_A.等到 CURENT_SSID 在 VC_A 成功更新。
  3. compare DEVICE_SSID and CURRENT_SSID.比较 DEVICE_SSID 和 CURRENT_SSID。
1. VC_A
// get current SSID and save to UserData.shared.current_wifi_ssid
    var ssid: String { 
        var return_ssid:String = "取得できませんでした。"
        if let interfaces = CNCopySupportedInterfaces() as NSArray? {
            for interface in interfaces {
                if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary?,
                    let ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String {
                    return_ssid = ssid
                }
            }
        }
        
        UserData.shared.current_wifi_ssid = return_ssid
        return return_ssid
    }
//catch when having wifi connection changing event
    func checkNetWorking() {
        monitor.pathUpdateHandler = { path in
            if path.status == .satisfied {
                self.isConnected = true
   //check sign in at backend
                Backend.shared.checkSignedIn {(isSignedIn: Bool) in
                    if !isSignedIn {
                        DispatchQueue.main.async {
                            AlertHelper.displayOK(self, title: "エラー", message: "サインインしてください")
                        }
                    }
                }
            } else {
     //the case no internet or already accessed to DEVICE_WIFI           
                //############# location - wifi
            do something
                //#############
            }
        }
    }

2. VC_B
//connect to device wifi and check
    func connectTheta(ID: String){
        TableVIew.isUserInteractionEnabled = false
        SVProgressHUD.show()
        let manager = NEHotspotConfigurationManager.shared
        let ssid = "THETAYN" + ID + ".OSC"
        let password = ID
        let isWEP = false
        let hotspotConfiguration = NEHotspotConfiguration(ssid: ssid, passphrase: password, isWEP: isWEP)
        hotspotConfiguration.joinOnce = true
        hotspotConfiguration.lifeTimeInDays = 1

        UserData.shared.current_wifi_ssid = "NULL"
        manager.apply(hotspotConfiguration) { (error) in //error always nil
            if error != nil {
            // error
          } else {
            // success
          }
            
            check_wifi_theta();
            
            func check_wifi_theta(){
      //i'm using while here to wait task from VC_A (wait until UserData.shared.current_wifi_ssid is updated)
                while(UserData.shared.current_wifi_ssid=="NULL"){
                    Thread.sleep(forTimeInterval: 0.5)
                }
                print("ssid theta", ssid)
                print("ssid current", UserData.shared.current_wifi_ssid)
                if (UserData.shared.current_wifi_ssid==ssid){
                    print("connect Theta OK")
                    AlertHelper.displayOK(self, title: "接続できました", message: "", okHandler: {_ in
                        self.navigationController?.popViewController(animated: true)
                    })
                }
                else{
                    AlertHelper.displayOK(self, title: "接続できません", message: "THETAの電源が入っている確認してください。")
                }
                self.TableVIew.isUserInteractionEnabled = true
                SVProgressHUD.dismiss()
            }
        }
    }

I am stuck at step 2 when trying to wait for "pathUpdateHandler" to finish from VC_B.当我试图等待“pathUpdateHandler”从 VC_B 完成时,我被困在第 2 步。 Sometimes it changes but sometimes it's not.有时它会改变,但有时不会。 I use while loop here and it's solved my problem.我在这里使用while循环,它解决了我的问题。 But I think it's is not the best choice.但我认为这不是最好的选择。 Is there any better solution for this?有没有更好的解决方案? Thanks!谢谢!

Firstly, it could be better to clean up yours example code.首先,清理您的示例代码可能会更好。 In your message it is difficult to understand what is going on.在您的信息中,很难理解发生了什么。

In my opinion it is a bad idea to use infinite while loops in this case.在我看来,在这种情况下使用无限 while 循环是个坏主意。 I can advice these options:我可以建议以下选项:

  1. NSLock NSLock

  2. Observe event in any way.以任何方式观察事件。 There are multiple options in iOS, depending on task. iOS 中有多个选项,具体取决于任务。 You can use delegate pattern and create a delegate protocol and add a reference on VC_B inside VC_A.您可以使用委托模式并创建委托协议并在 VC_A 内添加对 VC_B 的引用。 The similar method is closure usage (save and call closure instead of delegate).类似的方法是闭包使用(保存并调用闭包而不是委托)。

  3. Another option is using NotificationCenter to post notifications in VC_A and observe this event in VC_B.另一种选择是使用 NotificationCenter 在 VC_A 中发布通知并在 VC_B 中观察此事件。 It is basic observer pattern usage in iOS, but you can use more advanced techniques like creating your own observer pattern implementation, like multi-delegates observer.这是 iOS 中的基本观察者模式用法,但您可以使用更高级的技术,例如创建自己的观察者模式实现,例如多委托观察者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从ViewController访问Swift 3中的另一个viewController - How to access from viewController another viewController in Swift 3 等待 Swift 定时器完成 - Wait for Swift timers to finish 来自另一个 viewController 的快速检测 - iOS swift - swift detection from another viewController - iOS swift 如何在 ViewController 启动之前等待 AppDelegate 完成? - How to wait AppDelegate is finish before ViewController start? 如何快速将图像从一个视图控制器传递到另一个视图控制器? - How to pass an image from one viewcontroller to another viewcontroller in swift? 如何使用Swift 3将数据从ViewController A传递到另一个ViewController B - How to pass data from viewcontroller A to another viewcontroller B using swift 3 将对象从一个ViewController传递到另一个ViewController很快就无效了 - Passing an object from one viewcontroller to another viewcontroller got nil in swift Swift 3将数据从一个ViewController传递到另一个ViewController - Swift 3 pass data from one ViewController to another ViewController 将一个ViewController中的managedObjectContext传递给Swift中的另一个ViewController? - Passing an managedObjectContext from one ViewController to another ViewController in Swift? Swift:将数据从ViewController中的tableView传递到另一个ViewController - Swift: Passing data from a tableView in a ViewController to another ViewController
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM