swift - 如何延迟返回调用函数swift

标签 swift location delay

在我的应用程序中,用户可以按下一个按钮。这反过来会导致如下所示的函数调用:

在 ViewController.Swift 中

@IBAction func pickMeUpButton(sender: AnyObject) {

    sendPushNotificationController().sendPushNotification("sendRequest",userInfo: defaults.stringForKey("x73")!, userInf23: defaults.stringForKey("x23")! )

    locationController.getLocationForShortTime() // --> here i want the timer to finish the 5 seconds before proceeding

    activityIndicator.center = self.view.center

    activityIndicator.startAnimating()

    self.view.addSubview(activityIndicator)

    //activityIndicator.stopAnimating()

}

这是调用的类函数

在 getUserLocation.swift 中

func initManager(){

    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
}

func getLocationForShortTime(){

    initManager()
    timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "stopGettingLocation", userInfo: nil, repeats: false)

}

func stopGettingLocation(){

    locationManager.stopUpdatingLocation()
}

所以这将使应用程序获取用户位置 5 秒,然后计时器将停止更新。我想要做的是当五秒钟过去并且位置更新停止时然后我希望调用函数继续到下一行。

我虽然有一些使用 bool 值的解决方案,但这不是一个好的解决方案。我想可能有更好的方法来做到这一点?

最佳答案

其他人已经告诉你该做什么,但没有告诉你为什么。

你需要调整思路。

对于像 iPhone/iPad 这样的事件驱动设备,您不能在主线程上停止处理 5 秒。 UI 会锁定,几秒钟后系统会终止您的应用程序。

相反,您要做的是在延迟后调用代码块(闭包)。

你可以像这样重写你的函数:

@IBAction func pickMeUpButton(sender: AnyObject) 
{      
  sendPushNotificationController().sendPushNotification("sendRequest",
     userInfo: defaults.stringForKey("x73")!,
     userInf23: defaults.stringForKey("x23")! )

  initManager()

  //Start the activity indicator during the delay
  activityIndicator.center = self.view.center
  self.view.addSubview(activityIndicator)
  activityIndicator.startAnimating()

  dispatch_after(
    dispatch_time(DISPATCH_TIME_NOW, Int64(5.0 * Double(NSEC_PER_SEC))),
    dispatch_get_main_queue())
  {
    //The code in the braces gets run after the delay value
    locationManager.stopUpdatingLocation()
    activityIndicator.stopAnimating()
  }
  //dispatch_after returns immediately, so code here will run before
  //the delay period passes.
}

该按钮操作代码将:

调用 initManager 启动位置管理器运行。

立即创建一个事件指示器,将其添加到 View Controller 的内容 View 中,然后开始旋转。

然后,对 dispatch_after 的调用将等待 5 秒,然后运行大括号中的代码,这将停止位置管理器并停止事件指示器。

关于swift - 如何延迟返回调用函数swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34519519/

相关文章:

iphone - 如何以非阻塞延迟执行多个操作?

ios - 对成员 '==' 的模糊引用

swift - 如何使用 spriteKit 在 swift 中在 Sprite 图像或纹理中切一个洞以显示其背后的内容

ios - 模式转换后未调用 IBAction

iphone - 如何在 iPhone 中获取设备位置名称?

powershell - 延迟忽略CTRL + C-Powershell

json - 如何在 Alamofire 请求 swift 3 上发出警报

java - 如何让应用程序每次运行时都请求位置权限?

iphone - 在真实 iOS 设备上模拟位置

tcp - 错误 : ‘TCP_NODELAY’ was not declared in this scope