· 9 years ago · Jan 13, 2017, 12:12 PM
1func downloadFunc() {
2
3 let url = NSURL(string: "http://development.ssntpl.com/personal_record_api/downloaddescription.php");
4
5 let request = NSMutableURLRequest(URL:url!)
6
7 request.HTTPMethod = "POST"
8
9 let post:NSString = "user_id=(id)&month=True&date=(Month)&email=(Email)"
10
11 print(post)
12
13
14 request.HTTPBody = post.dataUsingEncoding(NSUTF8StringEncoding)
15
16
17 let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
18
19 data, response, error in
20
21 if error != nil
22 {
23 print("error is (error)")
24 return;
25 }
26
27 //parsing the response
28 do {
29
30 //converting response to NSDictionary
31 let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
32 //print("DOWNLOADED DATA")
33 //print(myJSON!)
34
35 //parsing the json
36 if let parseJSON = myJSON
37 {
38 let Status = parseJSON["status"] as! Int
39 let Code = parseJSON["code"] as! Int
40 //print("status:(Status)")
41 //print("code:(Code)")
42 if (Status == 1)
43 {
44
45
46 let Result = parseJSON["result"]!
47
48 //print("Result=(Result)")
49 //print("CHECKOUT")
50
51 for res in Result as! NSArray
52 {
53 let date = res["date"] as! String
54 let data = res["data"] as! String
55
56 print("data")
57 print(data)
58
59 if (data != "")
60 {
61 //ModelManager.sharedInstance.insertingRecordDataToDatabaseAfterDownload(self.id, email: self.Email, createdOn: date, record: data)
62
63 //function for Saving the DataRecords into the Database
64
65 let URL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil , create: false).URLByAppendingPathComponent("PersonalRecordAppDataBase.sqlite")
66
67
68
69 guard let recordDB = FMDatabase (path : URL.path) else
70 {
71 print("unable to create the database")
72 return
73 }
74 print(URL)
75
76
77 guard recordDB.open()
78 else
79
80 {
81 print("Database is not open or unable to connect")
82 return
83 }
84 do
85 {
86
87 try! recordDB.executeUpdate ("create table IF NOT EXISTS recordDataTable (ID integer, Email text, createdOn TEXT, updatedOn TEXT, Record text, Lastseen TEXT)" , values: nil);
88 try! recordDB.executeUpdate ("insert into recordDataTable (ID, Email, createdOn, updatedOn, Record, Lastseen) values(?,?,?,?,?,?)", values : [self.id, self.Email, date, self.Current! , data, ""])
89
90
91
92 }
93
94 catch let error as NSError
95 {
96 print("failed: (error.localizedDescription)")
97 }
98
99 recordDB.close()
100
101
102 }
103
104 let image = res["images"] as! NSArray
105 print(image.count)
106 //print(image)
107 //while (image.next != nil)
108 self.lastComponentArray.removeAll()
109 for item in image
110 {
111
112
113 if item as! String != ""
114 {
115 //print("image : (image)")
116
117 //print("CHECKEDIN")
118 //print(image)
119 print(item)
120
121
122 let url = NSURL(string: item as! String)
123
124
125 let request = NSURLRequest(URL: url!)
126 NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
127 {
128 (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
129
130
131
132 let imagedata = UIImage(data: data!)
133
134 let lastComponent = url?.lastPathComponent
135 //print("itemLASTCOMPONENT = (lastComponent!)")
136 self.lastComponentArray.append(lastComponent!)
137 //print(self.lastComponentArray)
138
139 //ModelManager.sharedInstance.insertingRecordImagesToDatabaseAfterDownload(self.id, email: self.Email, createdOn: date, lastComponent: lastComponent!)
140
141 // Saving images to the Document Directory
142
143 let fileManager = NSFileManager.defaultManager()
144 let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("/(lastComponent!)")
145 print("Imagepaths=(paths)")
146 let imageData = UIImageJPEGRepresentation(imagedata!, 0.2)
147 fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil)
148
149
150
151 //function for Saving the RecordImages into the Database
152
153 let URL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil , create: false).URLByAppendingPathComponent("PersonalRecordAppDataBase.sqlite")
154
155
156
157 guard let recordDB = FMDatabase (path : URL.path) else
158 {
159 print("unable to create the database")
160 return
161 }
162 print(URL)
163
164
165 guard recordDB.open()
166 else
167
168 {
169 print("Database is not open or unable to connect")
170 return
171 }
172 do
173 {
174 try recordDB.executeUpdate("create table IF NOT EXISTS recordImagesTable (ID integer, Email text, createdOn TEXT, updatedOn TEXT, recordImages NSDate)" , values: nil);
175 try! recordDB.executeUpdate ("insert into recordImagesTable (ID,Email,createdOn, updatedOn, recordImages) values(?,?,?,?,?)", values : [self.id, self.Email, date, self.Current!, lastComponent!, ""])
176
177
178 }
179 catch let error as NSError
180 {
181 print("failed: (error.localizedDescription)")
182 }
183
184 recordDB.close()
185
186 }
187 self.tableView.reloadData()
188
189
190 // print("lastComponentArray")
191 //print(self.lastComponentArray)
192
193 }
194
195
196
197
198 }
199 print("save to database")
200 // ModelManager.sharedInstance.insertingRecordImagesToDatabaseAfterDownload(self.id, email: self.Email, createdOn: date, lastComponent: self.lastComponentArray)
201
202
203 }
204
205 //showing the AlertView that Records has been Downloaded
206
207 let A = UIAlertController(title: "Done!!!", message: "Record downloaded", preferredStyle: .Alert)
208 let B = UIAlertAction(title: "ok", style:UIAlertActionStyle.Default, handler: nil)
209 A.addAction(B)
210 self.presentViewController(A, animated: true, completion: nil)
211
212 }
213
214 if (Status == 0)
215 {
216 print("No data for Selected month")
217 }
218
219
220 }
221
222 }
223
224
225 catch
226 {
227 print(error)
228 }
229
230
231
232 }
233 //executing the task
234 task.resume()
235
236DispatchQueue.main.async {
237 //here you can update UI
238 }
239
240dispatch_async(dispatch_get_main_queue()) {
241 //here you can update UI
242 }
243
244let A = UIAlertController(title: "Done!!!", message: "Record downloaded", preferredStyle: .Alert)
245let B = UIAlertAction(title: "ok", style:UIAlertActionStyle.Default, handler: nil)
246A.addAction(B)
247self.presentViewController(A, animated: true, completion: nil)
248
249self.tableView.reloadData()
250
251dispatch_async(dispatch_get_main_queue(), {
252 self.tableView.reloadData()
253})
254
255dispatch_async(dispatch_get_main_queue(), {
256 let A = UIAlertController(title: "Done!!!", message: "Record downloaded", preferredStyle: .Alert)
257 let B = UIAlertAction(title: "ok", style:UIAlertActionStyle.Default, handler: nil)
258 A.addAction(B)
259 self.presentViewController(A, animated: true, completion: nil)
260})
261
262DispatchQueue.main.async {
263 let A = UIAlertController(title: "Done!!!", message: "Record downloaded", preferredStyle: .Alert)
264 let B = UIAlertAction(title: "ok", style:UIAlertActionStyle.Default, handler: nil)
265 A.addAction(B)
266 self.presentViewController(A, animated: true, completion: nil)
267}
268
269DispatchQueue.main.async {
270 self.tableView.reloadData()
271}