Swift uitableview json delete row - ios

I have a tableview with JSON data where I can delete mysql data by JSON with Delete button action throw a method. But does not find out a way to delete from cell.
Here is screen shot and code
//Send user data to server side
#IBAction func deleteData(sender: AnyObject) {
let adduser = lblName.text
let id = store.storeId
//Send user data to server side
let myUrl = NSURL(string: "http://localhost/crud/delete.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "id=\(id)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{
data, response, error in
if error != nil {
print("error=\(error)")
return
}
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON=json{
var resultValue = parseJSON["status"] as! String
print("result: \(resultValue)")
var isUserRegistered:Bool = false;
if(resultValue=="Success") {isUserRegistered = true; }
var messageToDisplay:String = parseJSON["status"] as! String
if(!isUserRegistered)
{
messageToDisplay = parseJSON["message"] as! String;
}
//self.store.storeName = self.lblName.text!
//store?.sName = txtName.text!
self.store.storeName = self.lblName.text!
dispatch_async(dispatch_get_main_queue(), {
// Display alert message with confirmation.
var myAlert = UIAlertController(title:"Alert", message:messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default) {action in
self.dismissViewControllerAnimated(true, completion:nil);
}
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion:nil);
});
}
}catch{print(error)}
}
task.resume()
}
TableViewController
class TableViewController: UITableViewController {
var storeList = [Store]()
//var storeList:Store?
override func viewDidLoad() {
super.viewDidLoad()
/*
if let s = storeList
{
txtName.text = s.storeName
}
*/
// Uncomment the following line to preserve selection between presentations
//self.clearsSelectionOnViewWillAppear = true
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.loadRecords()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData() // to reload selected cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return storeList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! StoreTVC
let s = storeList[indexPath.row] as Store
cell.lblName.text = s.storeName
//cell.lblID.text = s.storeId
return cell
}
// for swipe delete
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
storeList.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
/*
if segue.identifier == "details"
{
//if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)
if let indexPath = tableView.indexPathForSelectedRow
{
let s = storeList[indexPath.row] as Store
let dvc = segue.destinationViewController as! ViewDetails
dvc.store = s
}
}
*/
if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)
{
let s = storeList[indexPath.row] as Store
let dvc = segue.destinationViewController as! ViewDetails
dvc.store = s
}
}
func loadRecords()
{
//The address of the web service
let urlString = "http://localhost/crud/read_for_table_view.php"
// 1 - Create the session by getting the configuration and then crrating the session
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config, delegate: nil, delegateQueue: nil)
//2 - Create the URL Object
if let url = NSURL(string: urlString)
{
//3 - Create the request object
let request = NSURLRequest(URL: url)
//4 - execute the request
let taskData = session.dataTaskWithRequest(request, completionHandler: {
(data: NSData?, response:NSURLResponse?, error: NSError?) -> Void in
//5 - Do something with the Data back
if(data != nil)
{
//we got some data back
print("\(data)")
/*
var parseError:NSError?
let parsedStores = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parseError) as! NSDictionary
*/
do {
if let parsedStores = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("Json Data \n \(parsedStores)")
if let stores:AnyObject = parsedStores["result"]
{
self.parseJSON(stores)
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
}else
{
//we got an error
print("Error getting stores :\(error!.localizedDescription)")
}
})
taskData.resume()
}
}
func parseJSON(jsonData:AnyObject)
{
if let storeData = jsonData as? [[NSObject:AnyObject]]
{
var store:Store
//we loop through all the recors and everytime we create
// an object of kind store and then add to the store list
for s in storeData
{
store = Store()
// this part is getting the values
if let sId:AnyObject = s["id"]
{
if let storeID = sId as? String
{
print("Store id = \(storeID)")
store.storeId = storeID
}
}
if let sn:AnyObject = s["name"]
{
if let storeName = sn as? String
{
store.storeName = storeName
}
}
storeList += [store]
}
NSOperationQueue.mainQueue().addOperationWithBlock()
{
self.tableView.reloadData()
}
}
}
}
Can someone please help?

After deleting data from mysql,
1) you will have to delete cell from tableview as follow.
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
in first argument you will have to pass array of indexpaths which cells you want to delete.
2) Or else you can again fetch data from Database & reload table..
//code for fetching data from database
self.tableView.reloadData()

There is basically 2 things ....
1st is just put your self.loadRecords() in viewWillAppear method
and 2nd one remove all objects from array before parse it once again like
func parseJSON(jsonData:AnyObject)
{
storeList.removeAll()
//....
}

Related

TableView not updating after button action

I'm relatively new to swift, and I'm trying to have a view that when it loads it will display some info on my tableView, then in the same view I have a textfield and a button
I want that the button performes an action that fetchs data from my server and updates my tableView
The problem is that the table is not being updated. How can I get the table to be updated?
CODE:
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 80;
tableView.tableFooterView = UIView();
self.url = URL(string: "http://xxxxxxxx.com/xxxxx/api/produtos/listagem/favoritos/\(userID)");
downloadJson(_url: url!);
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return produtos.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProdutoCell1") as? ProdutoCell else{
return UITableViewCell()
}
cell.lbl_nome_json.text = produtos[indexPath.row].nome;
cell.lbl_categoria_json.text = produtos[indexPath.row].categoria;
cell.lbl_loja_json.text = produtos[indexPath.row].loja
//= produtos[indexPath.row].categoria;
// cell.lbl_loja.text = produtos[indexPath.row].loja;
if let imageURL = URL(string: "http://xxxxxxxxxx.com/myslim/api/"+produtos[indexPath.row].url){
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL);
if let data = data{
let image = UIImage(data: data);
DispatchQueue.main.async {
cell.imgView_json.image = image;
}
}
}
}
return cell;
}
ACTION:
#IBAction func btn_search(_ sender: Any) {
if self.txt_search.text == "" {
let alert = UIAlertController(title:"Alert",message: "Insira algo para pesquisar",preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertAction.Style.default, handler: nil))
self.present(alert,animated: true,completion: nil)
}else{
var pesquisa = String();
pesquisa = self.txt_search.text!;
let url2 = URL(string: "http://xxxxxxxx.com/xxxxxx/api/produtos/listagem/favoritos/\(pesquisa)/\(self.userID)");
downloadJson(_url: url2!);
}
func downloadJson(_url: URL){
guard let downloadURL = url else {return}
URLSession.shared.dataTask(with: downloadURL){data, urlResponse, error in
guard let data = data, error == nil, urlResponse != nil else{
print("algo está mal");
return;
}
do{
let decoder = JSONDecoder();
let downloadedProdutos = try decoder.decode([ProdutoModel].self, from: data);
self.produtos = downloadedProdutos
print(downloadedProdutos);
DispatchQueue.main.async {
self.tableView.reloadData();
print("reload");
}
}catch{
print("algo mal depois do download")
}
}.resume();
}
EDIT
I added some print to see how many object were being returned on my downloadedProdutos variable, on the downloadJson() function.
And at the viewdidload I get 2 object, its normal because I only have 2 Products, but when the action is done I still get 2 object although I should get only 1 object
You need to set tableView.dataSource = self in viewWillAppear and it looks you missed func numberOfSections() -> Int method.
Add UITableViewDataSource like this
class YourViewController: UIViewController, UITableViewDataSource and it will recommend you required methods

Retrieving data back from server side based on input

I'm doing a school project, its's multiple tables and tabBarControllers. Now, I want to display return data back from server side based on selected row. I managed to pass selected row from View to another, and I believe there is nothing wrong with passing it to the server side, too. The problem is when retrieving the data back from the server.
Here is Course View
// This array is to hold data coming from server side
var course: NSArray = []
// Assign data that come from DepartmentView
public var department: String? = nil
var myURL = URL(string: "http://localhost/masterProject/scripts/courses.php")
override func viewDidLoad()
{
super.viewDidLoad()
self.title = "Courses"
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
// This is just to make sure it gets data and not nil
let vDepartment = department!
// Create a request
var request = URLRequest(url: myURL!)
request.httpMethod = "POST";
// Create a parameter to be sent to server side and based on this
// data I want to get data back that belong to it.
let postParameter = "department=\(vDepartment)";
request.httpBody = postParameter.data(using: String.Encoding.utf8)
// Here I Create and send dataTask
let task = URLSession.shared.dataTask(with: request)
{ (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
if(error != nil)
{
self.alertMessage(message: (error?.localizedDescription)!)
return
}
// This is supposed to read data from server side and display it
// in Course table view.
self.course = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSArray
}
}
task.resume()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return course.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "courseCell", for: indexPath) as! CourseTableViewCell
let main = course[indexPath.row] as! NSDictionary
cell.courseName.text = (main["name"] as! String)
cell.courseNumber.text = (main["number"] as! String)
return cell
}
func alertMessage(message: String)
{
let alert = UIAlertController(title: "Alert", message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
Department view
var departments: NSArray = []
var myURL = URL(string: "http://localhost/masterProject/scripts/department.php")
override func viewDidLoad()
{
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool)
{
self.title = "Departments"
super.viewWillAppear(animated)
let data = NSData(contentsOf: myURL!)
departments = try! JSONSerialization.jsonObject(with: data! as Data, options: .mutableContainers) as! NSArray
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
// #warning Incomplete implementation, return the number of rows
return departments.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let data = departments[indexPath.row] as! NSDictionary
cell.textLabel?.text = (data["name"] as! String)
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "showDepCourses"
{
if let indexPath = tableView.indexPathForSelectedRow
{
let courseVC = segue.destination as! CourseTableViewController
let data = departments[indexPath.row] as! NSDictionary
courseVC.department = (data["name"] as! String)
}
}
}
}
Here are the picture for both Views
department view
course view
I'm supposed get the right data based on selected row but instead it shows nothing.
self.tabeView.reloadData() was missing the whole time.
This is the answer for the question:
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
// Just to make sure "Optional" keyword not send as POST PERAMETER
let selectedDep = department!
// Create a request
var request = URLRequest(url: myURL!)
request.httpMethod = "POST";
// Create a parameter to be sent to server side and based on this
// data I want to get data back that belong to it.
let postParameter = "department=\(selectedDep)";
request.httpBody = postParameter.data(using: String.Encoding.utf8)
// Here I create and send dataTask
let task = URLSession.shared.dataTask(with: request)
{ (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
if(error != nil)
{
self.alertMessage(message: (error?.localizedDescription)!)
return
}
// This is supposed to read data from server side and display it
// in Course table view.
self.courses = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSArray
self.tableView.reloadData()
}
}
task.resume()
}

JSON TableView Swift Error

I'm trying to populate a tableview with this JSON URL. I validated the URL, and it works fine. My code is at fault. I have a 'Repository.swift' file with a class inside. Here's my code: I can't resolve the issue.
var repositories = [Repository]()
override func viewDidLoad() {
super.viewDidLoad()
let reposURL = NSURL(string: "https://www.kimonolabs.com/api/7flcy3qm?apikey=gNq3hB1j0NtBdAvXJLEFx8JaqtDG8y6Y")!
if let JSONData = NSData(contentsOfURL: reposURL) {
if let json = NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
if let reposArray = json["items"] as? [NSDictionary] {
for item in reposArray {
repositories.append(Repository(json: item))
}
}
}
}
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.repositories.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = repositories[indexPath.row].Event
cell.detailTextLabel?.text = repositories[indexPath.row].Hasta
return cell
}
You need to add try catch
I fixed your code
override func viewDidLoad() {
super.viewDidLoad()
let reposURL = NSURL(string: "https://www.kimonolabs.com/api/7flcy3qm?apikey=gNq3hB1j0NtBdAvXJLEFx8JaqtDG8y6Y")!
if let JSONData = NSData(contentsOfURL: reposURL) {
do{
let json = try NSJSONSerialization.JSONObjectWithData(JSONData, options: .MutableContainers)
if let reposArray = json["items"] as? [NSDictionary] {
for item in reposArray {
// repositories.append(Repository(json: item))
}
}
}catch {
//do whatever
}
}
}
Kindly try it.

Not all cells loading in tableview, getting a blank screen instead. Xcode/Swift

I am able add all core data and save it alright, and even print it all to the logs. However when I try to fetch the core data and load it on to the table view, only the first couple cells actually load and everything below the loaded cells is just a blank screen.
Here is my view controller:
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var loggedIn = false
var managedObjectContext: NSManagedObjectContext? = nil
var detailViewController: DetailViewController? = nil
#IBOutlet var tableViewLoginButton: UIBarButtonItem!
#IBAction func tableViewLoginButtonAction(sender: AnyObject) {
shouldPerformSegueWithIdentifier("loginSegue", sender: nil)
}
override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool {
if let ident = identifier {
if ident == "loginSegue" {
if loggedIn == true {
PFUser.logOutInBackgroundWithBlock({ (error) -> Void in
self.checkForUser()
})
return false
}
}
}
return true
}
func checkForUser() {
let currentUser = PFUser.currentUser()
if (currentUser != nil) {
loggedIn = true
tableViewLoginButton.title = "Logout"
} else {
loggedIn = false
tableViewLoginButton.title = "Login"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Code for Login and Sign Up
checkForUser()
coreDataSetup()
}
func coreDataSetup() {
// Code for fetching json data, saving as core data and loading to table view
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context : NSManagedObjectContext = appDel.managedObjectContext
let url = NSURL(string: "https://www.kimonolabs.com/api/6tewont8?apikey=CPMj8n9tabsEUqUjKEPiHOmVir5gZjfq")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!) { (data, response, error) -> Void in
if error != nil {
print(error)
} else {
// print(NSString(data: data!, encoding: NSUTF8StringEncoding))
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if jsonResult.count > 0 {
if let results = jsonResult["results"] as? NSDictionary {
if let eventData = results["collection1"] as? NSArray {
let request = NSFetchRequest(entityName: "ForumEvents")
request.returnsObjectsAsFaults = false
do {
let results = try context.executeFetchRequest(request)
if results.count > 0 {
for result in results {
context.deleteObject(result as! NSManagedObject)
do { try context.save() } catch {}
}
}
} catch {}
for event in eventData {
if let eventTitle = event["EventTitle"] as? NSDictionary {
if let eventTitleText = eventTitle["text"] as? String {
if let eventDate = event["EventDate"] as? String {
if let eventTicketLink = event["EventTicketLink"] as? NSDictionary {
if let eventLink = eventTicketLink["href"] as? String {
let newEvent : NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName("ForumEvents", inManagedObjectContext: context)
newEvent.setValue(eventTitleText, forKey: "eventTitle")
newEvent.setValue(eventDate, forKey: "eventDate")
newEvent.setValue(eventLink, forKey: "eventLink")
do { try context.save() } catch {}
}
}
}
}
}
}
}
}
}
self.tableView.reloadData()
} catch {}
}
}
task.resume()
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
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)
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
if segue.identifier == "loginSegue" {
checkForUser()
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
// Tried: return self.fetchedResultsController.fetchedObjects!.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath)
cell.textLabel!.text = object.valueForKey("eventTitle")!.description
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return false
}
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("ForumEvents", 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: "eventTitle", ascending: false)
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
do {
try _fetchedResultsController!.performFetch()
} catch {
// 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.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
}
Here is a screenshot of how the loaded cells turned out:
I have tried everything and have no idea what to try next!
Thanks in advance for any help.
Make sure the CoreData is correct. Then try this:
Change
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
}
into
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.fetchResultController.fetchedObjects!.count
}

Load JSON into UItableView in Swift

I've been trying to return string urls from JSON and store it in array and then show the array in UITableView. but it shows empty UILabel.
class PhotosTableViewController: UITableViewController {
let imageLoadURL = "https://..."
var TAG_IMG_URL = []
verride func viewDidLoad() {
super.viewDidLoad()
getLatestPhotos()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TAG_IMG_URL.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! KivaLoanTableViewCell
cell.nameLabel.text = TAG_IMG_URL[indexPath.row] as? String
return cell
}
func getLatestPhotos() {
let request = NSURLRequest(URL: NSURL(string: imageLoadURL)!)
let urlSession = NSURLSession.sharedSession()
let task = urlSession.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if error != nil {
println(error.localizedDescription)
}
self.TAG_IMG_URL = self.parseJsonData(data)
println("\(self.TAG_IMG_URL.count)")
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
})
task.resume()
}
func parseJsonData(data: NSData) -> NSArray {
var error:NSError?
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
if error != nil {
println(error?.localizedDescription)
}
if let j = jsonResult, let mediaObjects = j.valueForKeyPath("feed.entry.media$group.media$content") as? NSArray {
if let imageUrls: AnyObject = mediaObjects.valueForKey("url") {
TAG_IMG_URL = imageUrls as! NSArray
}
}
println("\(TAG_IMG_URL)")
self.alert.dismissWithClickedButtonIndex(0, animated: true)
return TAG_IMG_URL
}
}
During parseJsonData it returns the urls which it look like (below), but when i try to show it in the UITableView it always becomes empty UILabel so what am i doing wrong here ?:
(
(
"https://..."
),
(
"https://..."
)
)
Note : in numberOfRowsInSection it returns the right amount which its 2 urls.
Try this:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! KivaLoanTableViewCell
cell.nameLabel.text = TAG_IMG_URL[indexPath.row][0] as? String
return cell
}
The problem that you have 2-dimensional array, so you should get first object in object:
TAG_IMG_URL[indexPath.row].firstObject or TAG_IMG_URL[indexPath.row][0].

Resources