0

Result contains 1 data and any number of images on a particular date, I want to download records of any particular contact, save data in datTable and image in imagetable.

But I get the warning

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

My code is:

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

}

shallowThought
  • 19,212
  • 9
  • 65
  • 112
kunal kushwaha
  • 111
  • 1
  • 10
  • `NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())`. Why are you sending an asynchronousRequest in a mainQueue? – KrishnaCA Jan 13 '17 at 11:17
  • https://stackoverflow.com/a/50567382/8334818 This can be also possible solution – Pramod More Jun 05 '18 at 11:36

2 Answers2

0

to update UI you should call Main thread

put this code where you updating ui

swift 3 way

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

swift 2 way

    dispatch_async(dispatch_get_main_queue()) {
       //here you can update UI
    }
Vadim Kozak
  • 420
  • 3
  • 11
0

This simply means you're trying to make UI changes in background thread. Do it in main-thread.

Your UI related code:

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)

and

self.tableView.reloadData()

Do it in main-thread

For 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)
})

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

Feel free to suggest edits to make this better :)

KrishnaCA
  • 5,615
  • 1
  • 21
  • 31