【问题标题】:Timeout function after 10 seconds Swift/iOSSwift/iOS 10 秒后超时功能
【发布时间】:2017-03-03 05:48:36
【问题描述】:

如果在尝试连接 10 秒后登录没有成功,我想显示“网络错误”消息。

如何在 10 秒后停止登录功能并显示此错误消息?

我正在使用 AlamoFire。

我没有完整的实现,但这是我希望我的函数行为的框架:

func loginFunc() {

    /*Start 10 second timer, if in 10 seconds 
     loginFunc() is still running, break and show NetworkError*/


    <authentication code here>
}

【问题讨论】:

  • 用您希望超时的相关代码更新您的问题。
  • 更新了功能骨架。
  • 用您需要超时更新的实际工作代码更新您的问题。
  • 我还没有完整的工作代码。无论如何,完整的代码有什么关系?它只是调用数据库来检查用户/密码组合是否准确。
  • 网络调用有上千种方法,所以超时的能力取决于您的操作方式。

标签: ios swift timeout


【解决方案1】:

这是 Swift 4 的解决方案

DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
   // Excecute after 3 seconds
}

【讨论】:

    【解决方案2】:
    func delay(delay:Double, closure:()->()) {
        dispatch_after(
            dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), closure)
    }
    
    func loginFunc() {
    
        delay(10.0){
            //time is up, show network error
            //return should break out of the function (not tested)
            return
        }
    
        //authentication code
    

    【讨论】:

      【解决方案3】:

      如果你使用Alamofire,下面是定义超时的代码

      let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
      configuration.timeoutIntervalForRequest = 10 // seconds
      configuration.timeoutIntervalForResource = 10
      self.alamoFireManager = Alamofire.Manager(configuration: configuration)
      

      您也不需要通过计时器来管理它,因为计时器将在 10 秒后准确触发,与您的 API 是否得到响应无关,只需通过超时来管理它。

      这是你如何管理超时

      self.alamofireManager!.request(.POST, "myURL", parameters:params)
      .responseJSON { response in
          switch response.result {
              case .Success(let JSON):
                  //do json stuff
              case .Failure(let error):
                  if error._code == NSURLErrorTimedOut {
                     //call your function here for timeout
                  }
           }
      }
      

      【讨论】:

      • 谢谢拉贾特。超时时如何调用函数?假设我想在 AlamoFire 超时时拨打一些 myFunc()
      • 编辑了我的回答以处理超时,请检查。
      • 当我只使用Alamofire 时,我的请求工作正常。当我使用Alamorefire.Manager 时,它会显示NSErrorFailingURLStringKey
      • init() 解决方案对我不起作用,因为我的代码中没有任何 init() 调用。反正有没有将配置传递给Alamofire 本身?而不是经理?
      • 在 viedDidLoad 中试一试
      猜你喜欢
      • 1970-01-01
      • 2015-02-07
      • 2017-10-19
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      • 2012-04-08
      • 1970-01-01
      相关资源
      最近更新 更多