从服务器下载:"This application is modifying the autolayout engine ..."

Downloading from server: "This application is modifying the autolayout engine ..."

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

但我收到警告

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

我的代码是:

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()

}

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

将此代码放在更新的位置 ui

swift 3 路

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

swift 2 路

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

这仅仅意味着您正试图在后台线程中进行 UI 更改。在 main-thread.

中完成

您的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()

在main-thread

中完成

对于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()  
}

随时提出修改建议,使它变得更好:)