Advertisement
Guest User

Untitled

a guest
Mar 14th, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. class HomeModel: NSObject, URLSessionDataDelegate {
  2.  
  3. //properties
  4.  
  5. weak var delegate: HomeModelProtocal!
  6.  
  7. var data : NSMutableData = NSMutableData()
  8.  
  9. let urlPath: String = "http://iosquiz.com/service.php" //this will be changed to the path where service.php lives
  10.  
  11.  
  12. func downloadItems() {
  13.  
  14. let url: NSURL = NSURL(string: urlPath)!
  15. var session: URLSession!
  16. let configuration = URLSessionConfiguration.default
  17.  
  18.  
  19. session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
  20.  
  21. let task = session.dataTask(with: url as URL)
  22.  
  23. task.resume()
  24.  
  25. }
  26.  
  27. func parseJSON() {
  28.  
  29. var jsonResult: NSMutableArray = NSMutableArray()
  30.  
  31. do{
  32. jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray
  33.  
  34. } catch let error as NSError {
  35. print(error)
  36.  
  37. }
  38.  
  39. var jsonElement: NSDictionary = NSDictionary()
  40. let locations: NSMutableArray = NSMutableArray()
  41.  
  42.  
  43. for var i = 0; i < jsonResult.count; i+=1 {
  44.  
  45. jsonElement = jsonResult[i] as! NSDictionary
  46.  
  47. let user = UserModel()
  48.  
  49. //the following insures none of the JsonElement values are nil through optional binding
  50. if let id = jsonElement["id"] as? Int,
  51. let name = jsonElement["name"] as? String,
  52. let username = jsonElement["Username"] as? String,
  53. let password = jsonElement["Password"] as? String
  54. {
  55.  
  56. user.id = id
  57. user.name = name
  58. user.username = username
  59. user.password = password
  60. }
  61.  
  62. locations.addObject(user)
  63.  
  64. }
  65.  
  66. dispatch_async(dispatch_get_main_queue(), { () -> Void in
  67.  
  68. self.delegate.itemsDownloaded(items: user)
  69.  
  70. })
  71. }
  72.  
  73. func URLSession(session: URLSession, dataTask: URLSessionDataTask, didReceiveData data: NSData) {
  74. self.data.append(data as Data);
  75.  
  76. }
  77.  
  78. func URLSession(session: URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) {
  79. if error != nil {
  80. print("Failed to download data")
  81. }else {
  82. print("Data downloaded")
  83. self.parseJSON()
  84. }
  85.  
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement