xcode 此应用程序正在从后台线程修改自动布局引擎,这可能会导致引擎损坏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35594376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 08:34:34  来源:igfitidea点击:

This application is modifying the autolayout engine from a background thread, which can lead to engine corruption

xcodemultithreadingswift

提问by Ganesh Kumar

I am getting this error This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes.This will cause an exception in a future release.I don't know what is causing this error. Can anybody help me.

我收到此错误此应用程序正在从后台线程修改自动布局引擎,这可能导致引擎损坏和奇怪的崩溃。这将在未来版本中导致异常。我不知道是什么导致了这个错误。有谁能够帮助我。

func getUserDataFromTwitterWithUser(user : PFUser)
 {
//NRLoader.showLoader()
let strTwURL = "https://api.twitter.com/1.1/users/show.json?     screen_name="+PFTwitterUtils.twitter()!.screenName! + "&access_token="+PFTwitterUtils.twitter()!.authToken!
let twURL = NSURL (string: strTwURL)

let request = NSMutableURLRequest(URL: twURL!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 2.0) as NSMutableURLRequest

PFTwitterUtils.twitter()?.signRequest(request)

let session = NSURLSession.sharedSession()

session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
  if error == nil {
    var  jsonOptional = Dictionary<String, AnyObject>()

    do {
      jsonOptional = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! Dictionary<String, AnyObject>
      // use jsonData
    } catch {
      // report error
    }
    var userName = ""
    if let screenName = jsonOptional["screen_name"] as? String{
      userName = screenName
    }
    else if let name = jsonOptional["name"] as? String{
      userName = name
    }

    var profilePicUrl = ""


    if let picUrl = jsonOptional["profile_image_url"] as? String{
      profilePicUrl = picUrl
    }
    AppUser.currentUser()?.username = userName
    AppUser.currentUser()?.profileAwsURL = profilePicUrl
    //NRLoader.hideLoader()
    //if ParseUtils.isLoggedInUserIsAnonymous() {
      let signUpVC:SignMeUpViewController = self.storyboard!.instantiateViewControllerWithIdentifier("SignMeUpViewController") as! SignMeUpViewController
      signUpVC.isFromLogin = true
      self.navigationController!.pushViewController(signUpVC, animated: true)

    //} else {
     // self.pushToSubmitDreamViewController()
    //}
  }
  else {
    //NRLoader.hideLoader()
    NRToast.showToastWithMessage(error!.description)
  }


}).resume()
 }

回答by Michael

The dataTaskWithRequestcall runs in the background and then calls your completion handler from the same thread. Anything that updates the UI should run on the main thread, so all of your current handler code should be within a dispatch_asyncback onto the main queue:

dataTaskWithRequest调用在后台运行,然后从同一线程调用您的完成处理程序。任何更新 UI 的内容都应该在主线程上运行,因此您当前的所有处理程序代码都应该dispatch_async回到主队列中:

dispatch_async(dispatch_get_main_queue()) {
  // Do stuff to UI
}

Swift 3:

斯威夫特 3:

DispatchQueue.main.async() {
  // Do stuff to UI
}

Therefore, ideally all the code you currently have within if error == nilshould be off in another function, say called handleRequest, so your current code becomes:

因此,理想情况下,您当前拥有的所有代码都if error == nil应该在另一个函数中关闭,例如称为 handleRequest,因此您当前的代码变为:

session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
    if error == nil {
        dispatch_async(dispatch_get_main_queue(), {
            self.handleRequest(...)I
        })
    }

回答by Vimal Saifudin

Swift 3

斯威夫特 3

session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if error == nil {
    DispatchQueue.main.async {
        self.handleRequest(...)I
    }
}

回答by Abdul Hameed

Should try Symbolic Breakpoint to detect the issue:-enter image description here

应该尝试符号断点来检测问题:-在此处输入图片说明

Then put your UI Update code in main thread

然后将您的 UI 更新代码放在主线程中

DispatchQueue.main.async {}

回答by Kris Roofe

You'd better change UI only in the main thread

你最好只在主线程中更改 UI

swift3,

迅捷3,

    let liveInfoUrl = URL(string: "http://192.168.1.66/api/cloud/app/liveInfo/7777")
    let task = URLSession.shared.dataTask(with: liveInfoUrl! as URL) {data, response, error in
        guard let data = data, error == nil else { return }
        DispatchQueue.main.async {
            print(String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) ?? "aaaa")

            //do some ui work
        }
    }

回答by aremvee

if the above suggestions still give you no joy then the sure-est way is to redesign your functions so that getting what you need with

如果上述建议仍然没有让您感到高兴,那么最可靠的方法是重新设计您的功能,以便获得您需要的功能

 URLSession.shared.dataTask

then hands over so a variable declared outside that function, then a separate UIControl ( button, swipe etc ) displays it to a label or textview or whatever.

然后移交一个在该函数之外声明的变量,然后一个单独的 UIControl(按钮、滑动等)将它显示到标签或文本视图或其他任何东西。

After all that is what the error message is telling you. they're separate concerns

毕竟这就是错误消息告诉你的。他们是不同的关注点