从服务器下载:“此应用程序正在修改自动布局引擎......” [重复]

Posted

技术标签:

【中文标题】从服务器下载:“此应用程序正在修改自动布局引擎......” [重复]【英文标题】:Downloading from server: "This application is modifying the autolayout engine ..." [duplicate] 【发布时间】:2017-01-13 10:49:34 【问题描述】:

结果包含特定日期的 1 个数据和任意数量的图像,我想下载任何特定联系人的记录,将数据保存在 datTable 中,并将图像保存在 imagetable 中。

但我收到警告

此应用程序正在从后台线程修改自动布局引擎,这可能会导致引擎损坏和奇怪的崩溃,这将在未来的版本中导致异常

我的代码是:

func downloadFunc() 

    let url = NSURL(string: "http://development.ssntpl.com/personal_record_api/downloaddescription.php");

    let request = NSMutableURLRequest(URL:url!)

    request.HTTPMethod = "POST"

    let post:NSString = "user_id=\(id)&month=True&date=\(Month)&email=\(Email)"

    print(post)


    request.HTTPBody = post.dataUsingEncoding(NSUTF8StringEncoding)


    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) 

    data, response, error in

    if error != nil
    
          print("error is \(error)")
          return;
    

    //parsing the response
    do 

          //converting response to NSDictionary
          let myJSON =  try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
          //print("DOWNLOADED DATA")
          //print(myJSON!)

          //parsing the json
          if let parseJSON = myJSON
          
                let Status = parseJSON["status"] as! Int
                let Code = parseJSON["code"] as! Int
                //print("status:\(Status)")
                //print("code:\(Code)")
                if (Status == 1)
                


                      let Result = parseJSON["result"]!

                      //print("Result=\(Result)")
                      //print("CHECKOUT")

                      for res in Result as! NSArray
                      
                            let date = res["date"] as! String
                            let data = res["data"] as! String

                            print("data")
                            print(data)

                            if (data != "")
                            
                                   //ModelManager.sharedInstance.insertingRecordDataToDatabaseAfterDownload(self.id, email: self.Email, createdOn: date, record: data)

                                  //function for Saving the DataRecords into the Database

                                  let URL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil , create: false).URLByAppendingPathComponent("PersonalRecordAppDataBase.sqlite")



                                  guard let recordDB = FMDatabase (path : URL.path) else
                                  
                                        print("unable to create the database")
                                        return
                                  
                                  print(URL)


                                  guard recordDB.open()
                                        else

                                  
                                        print("Database is not open or unable to connect")
                                        return
                                  
                                  do
                                  

                                        try! recordDB.executeUpdate ("create table  IF NOT EXISTS recordDataTable (ID integer, Email text, createdOn TEXT, updatedOn TEXT,  Record text, Lastseen TEXT)" , values: nil);
                                        try! recordDB.executeUpdate ("insert into recordDataTable (ID, Email, createdOn, updatedOn, Record, Lastseen) values(?,?,?,?,?,?)", values : [self.id, self.Email, date, self.Current! , data, ""])



                                  

                                  catch let error as NSError
                                  
                                        print("failed: \(error.localizedDescription)")
                                  

                                  recordDB.close()


                            

                            let image = res["images"] as! NSArray
                            print(image.count)
                            //print(image)
                            //while (image.next != nil)
                            self.lastComponentArray.removeAll()
                            for item in image
                            


                                  if item as! String != ""
                                  
                                        //print("image : \(image)")

                                        //print("CHECKEDIN")
                                        //print(image)
                                        print(item)


                                        let url = NSURL(string: item as! String)


                                        let request = NSURLRequest(URL: url!)
                                        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
                                              
                                                    (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in



                                                    let imagedata = UIImage(data: data!)

                                                    let lastComponent = url?.lastPathComponent
                                                    //print("itemLASTCOMPONENT = \(lastComponent!)")
                                                    self.lastComponentArray.append(lastComponent!)
                                                    //print(self.lastComponentArray)

                                                    //ModelManager.sharedInstance.insertingRecordImagesToDatabaseAfterDownload(self.id, email: self.Email, createdOn: date, lastComponent: lastComponent!)

                                                    // Saving images to the Document Directory

                                                    let fileManager = NSFileManager.defaultManager()
                                                    let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("/\(lastComponent!)")
                                                    print("Imagepaths=\(paths)")
                                                    let imageData = UIImageJPEGRepresentation(imagedata!, 0.2)
                                                    fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil)



                                                    //function for Saving the RecordImages into the Database

                                                    let URL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil , create: false).URLByAppendingPathComponent("PersonalRecordAppDataBase.sqlite")



                                                    guard let recordDB = FMDatabase (path : URL.path) else
                                                    
                                                          print("unable to create the database")
                                                          return
                                                    
                                                    print(URL)


                                                    guard recordDB.open()
                                                          else

                                                    
                                                          print("Database is not open or unable to connect")
                                                          return
                                                    
                                                    do
                                                    
                                                          try recordDB.executeUpdate("create table IF NOT EXISTS recordImagesTable (ID integer, Email text, createdOn TEXT, updatedOn TEXT, recordImages NSDate)" , values: nil);
                                                          try! recordDB.executeUpdate ("insert into recordImagesTable (ID,Email,createdOn, updatedOn, recordImages) values(?,?,?,?,?)", values : [self.id, self.Email, date, self.Current!, lastComponent!, ""])


                                                    
                                                    catch let error as NSError
                                                    
                                                          print("failed: \(error.localizedDescription)")
                                                    

                                                    recordDB.close()

                                        
                                        self.tableView.reloadData()


                                        // print("lastComponentArray")
                                        //print(self.lastComponentArray)

                                  




                            
                            print("save to database")
                            // ModelManager.sharedInstance.insertingRecordImagesToDatabaseAfterDownload(self.id, email: self.Email, createdOn: date, lastComponent: self.lastComponentArray)


                      

                      //showing the AlertView that Records has been Downloaded

                      let A = UIAlertController(title: "Done!!!", message: "Record downloaded", preferredStyle: .Alert)
                      let B = UIAlertAction(title: "ok", style:UIAlertActionStyle.Default, handler: nil)
                      A.addAction(B)
                      self.presentViewController(A, animated: true, completion: nil)

                

                if (Status == 0)
                
                      print("No data for Selected month")
                


          

    


    catch
    
          print(error)
    



  
  //executing the task
  task.resume()

【问题讨论】:

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())。为什么要在 mainQueue 中发送异步请求? ***.com/a/50567382/8334818这也是可能的解决方案 【参考方案1】:

要更新 UI 你应该调用主线程

把这段代码放在你更新 ui 的地方

快速 3 路

    DispatchQueue.main.async 
        //here you can update UI
    

快速 2 路

    dispatch_async(dispatch_get_main_queue()) 
       //here you can update UI
    

【讨论】:

非常感谢......它对我有用。【参考方案2】:

这仅仅意味着您正在尝试在后台线程中进行 UI 更改。在主线程中执行。

您的 UI 相关代码:

let A = UIAlertController(title: "Done!!!", message: "Record downloaded", preferredStyle: .Alert)
let B = UIAlertAction(title: "ok", style:UIAlertActionStyle.Default, handler: nil)
A.addAction(B)
self.presentViewController(A, animated: true, completion: nil)

self.tableView.reloadData()

在主线程中做

对于 Swift 2:

dispatch_async(dispatch_get_main_queue(), 
   self.tableView.reloadData()         
)

dispatch_async(dispatch_get_main_queue(), 
   let A = UIAlertController(title: "Done!!!", message: "Record downloaded", preferredStyle: .Alert)
   let B = UIAlertAction(title: "ok", style:UIAlertActionStyle.Default, handler: nil)
   A.addAction(B)
   self.presentViewController(A, animated: true, completion: nil)
)

对于 Swift 3:

DispatchQueue.main.async 
    let A = UIAlertController(title: "Done!!!", message: "Record downloaded", preferredStyle: .Alert)
    let B = UIAlertAction(title: "ok", style:UIAlertActionStyle.Default, handler: nil)
    A.addAction(B)
    self.presentViewController(A, animated: true, completion: nil)      


DispatchQueue.main.async 
    self.tableView.reloadData()  

请随时提出修改建议以使其更好:)

【讨论】:

以上是关于从服务器下载:“此应用程序正在修改自动布局引擎......” [重复]的主要内容,如果未能解决你的问题,请参考以下文章

从服务器一个一个下载文件

从服务器下载文件的最佳方法是啥

从nodejs服务器下载文件在客户端下载为损坏的文件

无法从服务器下载 PKpass

从 FTP 服务器检查和下载多个文件

IOS InAppPurchase 内容从我自己的服务器下载