tanvir tanvir - 5 months ago 41
Swift Question

Swift uitableview json delete row

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

enter image description here

//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?

Answer

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()
       //....
  }