Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class HomeModel: NSObject, URLSessionDataDelegate {
- //properties
- weak var delegate: HomeModelProtocal!
- var data : NSMutableData = NSMutableData()
- let urlPath: String = "http://iosquiz.com/service.php" //this will be changed to the path where service.php lives
- func downloadItems() {
- let url: NSURL = NSURL(string: urlPath)!
- var session: URLSession!
- let configuration = URLSessionConfiguration.default
- session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
- let task = session.dataTask(with: url as URL)
- task.resume()
- }
- func parseJSON() {
- var jsonResult: NSMutableArray = NSMutableArray()
- do{
- jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray
- } catch let error as NSError {
- print(error)
- }
- var jsonElement: NSDictionary = NSDictionary()
- let locations: NSMutableArray = NSMutableArray()
- for var i = 0; i < jsonResult.count; i+=1 {
- jsonElement = jsonResult[i] as! NSDictionary
- let user = UserModel()
- //the following insures none of the JsonElement values are nil through optional binding
- if let id = jsonElement["id"] as? Int,
- let name = jsonElement["name"] as? String,
- let username = jsonElement["Username"] as? String,
- let password = jsonElement["Password"] as? String
- {
- user.id = id
- user.name = name
- user.username = username
- user.password = password
- }
- locations.addObject(user)
- }
- dispatch_async(dispatch_get_main_queue(), { () -> Void in
- self.delegate.itemsDownloaded(items: user)
- })
- }
- func URLSession(session: URLSession, dataTask: URLSessionDataTask, didReceiveData data: NSData) {
- self.data.append(data as Data);
- }
- func URLSession(session: URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) {
- if error != nil {
- print("Failed to download data")
- }else {
- print("Data downloaded")
- self.parseJSON()
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement