/gist:a9791a82061f156afdb9 Secret
Created
June 7, 2015 17:53
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import CoreData | |
var loggedIn = 0 | |
var currentTeamId = 0 | |
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate { | |
var managedObjectContext: NSManagedObjectContext? = nil | |
override func awakeFromNib() { | |
super.awakeFromNib() | |
} | |
override func viewWillAppear(animated: Bool) { | |
var appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate | |
var context: NSManagedObjectContext = appDel.managedObjectContext! | |
if loggedIn == 0 { | |
self.performSegueWithIdentifier("loginView", sender: self); | |
} | |
else { | |
let userUrl = NSURL(string: "http://52.11.75.34/users.php?username=\(currentUsername)") | |
let userSession = NSURLSession.sharedSession() | |
let userTask = userSession.dataTaskWithURL(userUrl!, completionHandler: { (data, response, error) -> Void in | |
if error != nil { | |
println(error) | |
} | |
else { | |
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary | |
if jsonResult.count > 0 { //means that there's something in the jsonResult | |
if let nbaTeamId = jsonResult["nbaTeam"] as? Int { | |
currentTeamId = nbaTeamId | |
} | |
} | |
} | |
}) | |
userTask.resume() | |
while currentTeamId == 0 { | |
println("Current Team Id 0") | |
} | |
let url = NSURL(string: "http://52.11.75.34/NBARSS.php?team=\(currentTeamId)") | |
let session = NSURLSession.sharedSession() | |
let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in | |
if error != nil { | |
println(error) | |
} | |
else { | |
//println(NSString(data: data, encoding: NSUTF8StringEncoding)) //How to print out the JSON | |
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary | |
if jsonResult.count > 0 { //means that there's something in the jsonResult | |
if let items = jsonResult["items"] as? NSArray { | |
var request = NSFetchRequest(entityName: "Posts") | |
request.returnsObjectsAsFaults = false | |
var results = context.executeFetchRequest(request, error: nil)! | |
if results.count > 0 { | |
for result in results { | |
context.deleteObject(result as! NSManagedObject) | |
context.save(nil) | |
} | |
} | |
for item in items { | |
//println(item) | |
if let title = item["title"] as? String { | |
if let link = item["link"] as? String { | |
var newPost: NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName("Posts", inManagedObjectContext: context) as! NSManagedObject | |
newPost.setValue(title, forKey: "title") | |
newPost.setValue(link, forKey: "link") | |
context.save(nil) | |
} | |
} | |
} | |
} | |
} | |
var request = NSFetchRequest(entityName: "Posts") | |
request.returnsObjectsAsFaults = false | |
var results = context.executeFetchRequest(request, error: nil)! | |
println(results) | |
dispatch_async(dispatch_get_main_queue(), { () -> Void in | |
self.tableView.reloadData() | |
}) | |
//self.tableView.reloadData() | |
} | |
}) | |
task.resume() | |
} | |
} | |
override func viewDidAppear(animated: Bool) { | |
dispatch_async(dispatch_get_main_queue(), { () -> Void in | |
self.tableView.reloadData() | |
}) | |
} | |
func update() { | |
dispatch_async(dispatch_get_main_queue(), { () -> Void in | |
self.tableView.reloadData() | |
}) | |
println("Reload Table") | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("update"), userInfo: nil, repeats: true) | |
// Do any additional setup after loading the view, typically from a nib. | |
/*self.navigationItem.leftBarButtonItem = self.editButtonItem() | |
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") | |
self.navigationItem.rightBarButtonItem = addButton*/ | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
// MARK: - Segues | |
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { | |
if segue.identifier == "showDetail" { | |
if let indexPath = self.tableView.indexPathForSelectedRow() { | |
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject | |
(segue.destinationViewController as! DetailViewController).detailItem = object | |
} | |
} | |
} | |
// MARK: - Table View | |
override func numberOfSectionsInTableView(tableView: UITableView) -> Int { | |
//return self.fetchedResultsController.sections?.count ?? 0 | |
return 1 | |
} | |
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
let sectionInfo = self.fetchedResultsController.sections![section] as! NSFetchedResultsSectionInfo | |
return sectionInfo.numberOfObjects | |
//return 3 | |
} | |
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell | |
self.configureCell(cell, atIndexPath: indexPath) | |
//cell.textLabel?.text = "Test" | |
return cell | |
} | |
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { | |
// Return false if you do not want the specified item to be editable. | |
return true | |
} | |
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { | |
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject | |
cell.textLabel!.text = object.valueForKey("title")!.description | |
} | |
// MARK: - Fetched results controller | |
var fetchedResultsController: NSFetchedResultsController { | |
if _fetchedResultsController != nil { | |
return _fetchedResultsController! | |
} | |
let fetchRequest = NSFetchRequest() | |
// Edit the entity name as appropriate. | |
let entity = NSEntityDescription.entityForName("Posts", inManagedObjectContext: self.managedObjectContext!) | |
fetchRequest.entity = entity | |
// Set the batch size to a suitable number. | |
fetchRequest.fetchBatchSize = 20 | |
// Edit the sort key as appropriate. | |
let sortDescriptor = NSSortDescriptor(key: "title", ascending: false) | |
let sortDescriptors = [sortDescriptor] | |
fetchRequest.sortDescriptors = [sortDescriptor] | |
// Edit the section name key path and cache name if appropriate. | |
// nil for section name key path means "no sections". | |
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master") | |
aFetchedResultsController.delegate = self | |
_fetchedResultsController = aFetchedResultsController | |
var error: NSError? = nil | |
if !_fetchedResultsController!.performFetch(&error) { | |
// Replace this implementation with code to handle the error appropriately. | |
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. | |
//println("Unresolved error \(error), \(error.userInfo)") | |
abort() | |
} | |
return _fetchedResultsController! | |
} | |
var _fetchedResultsController: NSFetchedResultsController? = nil | |
func controllerWillChangeContent(controller: NSFetchedResultsController) { | |
self.tableView.beginUpdates() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment