ios - 我该怎么做 : library's callback wait until user choose from popover and then get return

标签 ios swift

我无法理解如何使用 View /委托(delegate)和完成。

我使用具有回调的库 - 例如: func youShouldChoose()->String.

我想给用户一个选择并打开弹出窗口。但我不明白如何返回选定的值。

我阅读了有关完成的信息。所以我试过这个:

func youShouldChoose() -> String {        
       askUser() 

       return self.valueForResult    //This line is executed earlier than askUser is finished
    }


func  askUser(){
          showAlert(completion: {(result)->Void in
           self.valueForResult = result
    })
}


func showAlert(completion:@escaping (_ result:String)->Void)
    {
        let alert = UIAlertController(...)
        alert.addAction(UIAlertAction(title: "Click", style: UIAlertAction.Style.default, handler: { action in
              completion(textField.text)
        }))
        alert.addTextField(configurationHandler: {(textField: UITextField!) in
            textField.placeholder = "Enter text:"
     })

        self.present(alert, animated: true, completion: nil )
     }

我如何才能等到 askUser() 完全结束?有没有办法将完成后的值返回到我的库中?

最佳答案

我找到了两种方法来解决这个问题: 1.使用循环。显示 View 直到标志为 false

askUser() //we should set flag to true here  
while( flag == false ) {
    CFRunLoopRunInMode(CFRunLoopMode.defaultMode, 1, true);
}
return self.valueForResult 
  1. 使用信号量

    let semaphore = DispatchSemaphore(value: 0)
    askUser()   
    semaphore.lock()
    return self.valueForResult 
    

关于ios - 我该怎么做 : library's callback wait until user choose from popover and then get return,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57453390/

相关文章:

ios:根据前一个 View 中使用的segue,与另一个 View 不同的segue

IOS - Swift 字符类型的 ObjC NSObject 等价物是什么?

ios - 圆角改变 UIView 大小

Swift - 图像不显示

ios - 类似愤怒的小鸟游戏的Spritekit ios游戏弹弓机制

ios - 实现 facebook Ios SDK v4.0.1

ios - 通过 Storyboard或以编程方式在 Swift 中仅将深色模式强制为一个 UI 元素

ios - 如果在GCD中为队列创建相同的名称,它是同一个队列吗?

swift - 如何快速添加/更新字典中的键/值?

swift - 用户输入时自动将字符添加到 searchBar textField?