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