【问题标题】:Correct asynchronous Authentication while keeping a responsive UI在保持响应式 UI 的同时更正异步身份验证
【发布时间】:2015-05-06 19:20:36
【问题描述】:

应该是什么 我有一个用户名字段。当输入用户名并单击 sendButton 时,将使用 asynchronousRequest 作为 JSON 文件获取用户数据。 点击 sendButton 后,我想显示一个 ActivityIndi​​cator。 发出请求时,UI 仍应是响应式的。

现在的情况 我单击 sendButton 并且 UI 冻结。甚至 ActivityIndi​​cator 也不会显示。

代码

登录VC

func buttonTouchedUpInside(sender: UIButton) {
  toggleActivityIndicatorVisibilityOn(true) 
  LoginManager.sharedInstance.checkUserForCredentials(username: textFieldLogin.text, password: "")       
  toggleActivityIndicatorVisibilityOn(false)
}

func loginManagerDidFinishAuthenticationForUser(userData: [String:String]?){
    //  Delegate Method, which works with the fetched userData.
}

登录管理器

func checkUserForCredentials(#username: String ,password: String) -> Void {
  let url = NSURL(string: "\(Config.checkCredentialsUrl)username=\(username)")
  let request = NSURLRequest(URL: url!)
  NSURLConnection.sendAsynchronousRequest(request, queue: .mainQueue()) { (response, data, error) -> Void in
    if error != nil {
      //Display error-message
    }
  var error : NSError?
  let json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &error) as? [String:String]
  self.delegate?.loginManagerDidFinishAuthenticationForUser(json)      
  }
}

简而言之:我希望在后台发出请求,显示 Activityindicator 并且 UI 保持响应。异步请求成功获取json后,调用委托方法

【问题讨论】:

    标签: swift asynchronous nsurlrequest nsoperationqueue


    【解决方案1】:

    buttonTouchedUpInside 方法中的第二行代码,即 LoginManager.sharedInstance.checkUserForCredentials(username: textFieldLogin.text, password: ""),正在调用其中的异步函数,这意味着它不会阻塞下一行代码...我猜)触发你的加载屏幕再次变得不可见。

    基本上,您的加载屏幕会显示出来,但它会立即再次被隐藏。要至少修复加载屏幕的部分,请将第三行代码放在回调方法 loginManagerDidFinishAuthenticationForUser 中的 buttonTouchedUpInside 函数中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2020-03-06
      • 1970-01-01
      相关资源
      最近更新 更多