ReloadData与Alamofire无法正常工作

时间:2016-05-08 17:35:04

标签: ios uitableview alamofire reloaddata

我在添加新项目后尝试重新加载UITableView。当我尝试使用reloadData()时,它无效。没有显示任何内容。 如果我尝试重新加载getallrecords函数,则会重新加载项目,但会重复这些项目。 我的源代码是:

class FriendsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
    @IBOutlet var tabeview: UITableView!
    var textArray: NSMutableArray! = NSMutableArray()
    var subArray: NSMutableArray! = NSMutableArray()
    let defaults = NSUserDefaults.standardUserDefaults()
    var valueToPass:String!
    var reports_d:String!
    var reports:String!

@IBOutlet var menuButton: UIBarButtonItem!
@IBOutlet var friends_icon: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
     tabeview.dataSource = self
    tabeview.delegate = self
    tabeview.emptyDataSetSource = self
    tabeview.emptyDataSetDelegate = self
    tabeview.tableFooterView = UIView()

    getallrecords()
    self.tabeview.addPullToRefresh({ [weak self] in
        // refresh code
        self!.getallrecords()
        self?.tabeview.stopPullToRefresh()
        })
   // Do any additional setup after loading the view.
}



func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.textArray.count   
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
    cell.textLabel?.text = self.textArray.objectAtIndex(indexPath.row) as? String
    cell.detailTextLabel?.text = self.subArray.objectAtIndex(indexPath.row) as? String
    return cell   
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("You selected cell #\(indexPath.row)!")

    // Get Cell Label
    let indexPath = tableView.indexPathForSelectedRow!
    let currentCell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell

    valueToPass = currentCell.textLabel!.text
    reports = reports_d
    performSegueWithIdentifier("friends_details", sender: self)
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.Delete) {
        // handle delete (by removing the data from your array and updating the tableview)
        let currentCell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell
        let friend2 = currentCell.textLabel!.text

        let defaults = NSUserDefaults.standardUserDefaults()
        let username = defaults.objectForKey("name") as! String
        Alamofire.request(.GET, "http://www.example.com/app/remove_friends.php", parameters: ["key_id": "xxxxx","user_id": username,"friend_receive_id": friend2!, "action": "delete"])
            .response { request, response, data, error in
                print(request)
                print(response)
                print(error)
                if(error == nil)
                {
                    self.tabeview.beginUpdates()
                    self.textArray.removeObjectAtIndex(indexPath.row)
                    self.subArray.removeObjectAtIndex(indexPath.row)
                    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
                    self.tabeview.endUpdates()

                }

        }

   NSNotificationCenter.defaultCenter().postNotificationName("reloadData",object: self)

    }
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){

    if (segue.identifier == "friends_details") {

        // initialize new view controller and cast it as your view controller
        let viewController = segue.destinationViewController as! DetailsFriendsViewController
        // your new view controller should have property that will store passed value
        viewController.passedValue = valueToPass
        viewController.reports = reports
    }

}
func getallrecords(){
        if(defaults.stringForKey("name") != nil ){
            let username = defaults.objectForKey("name") as! String
            let full = "http://www.example.com/app/danger_friend_view.php?search=true&username=" + username
            let url = NSURL(string: full)
            let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
                do {
                    let d = NSString(data: data!, encoding: NSUTF8StringEncoding)
                    var arr = d!.componentsSeparatedByString("<") // spliting the incoming string from "<" operator because before that operator is our required data and storing in array
                    let dataweneed:NSString = arr[0] as NSString // arr[0] is the data before "<" operator and arr[1] is actually no use for us
                    NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                        SwiftSpinner.hide()
                        do {
                            if let data = try NSJSONSerialization.JSONObjectWithData(dataweneed.dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSJSONReadingOptions.MutableContainers]) as? NSArray {
                                for dd in data{
                                    var name : String = dd["danger"]! as! String
                                    self.reports_d = name
                                    let info : String = dd["username"]! as! String
                                    name = NSLocalizedString("SEND_ALERT_BEGIN",comment:"SEND_ALERT") + name + NSLocalizedString("ALERTS",comment:"ALERTS")
                                    print("ID is : \(name)")
                                    print("Username is : \(info)") 
                                    self.textArray.addObject(info)
                                    self.subArray.addObject(name)
                                }
                                self.tabeview.reloadData()
                            }
                        } catch let error as NSError {
                            print(error.localizedDescription)
                        }

                    })
                }
            }

            task.resume()
        }
    else
        {
   //Do something
        } 
     }

@IBAction func reload_data(sender: UIButton) {
    let banner = Banner(title: NSLocalizedString("RELOAD_DATA_TITLE",comment:"I'm in danger, I'm currently at  "), subtitle: NSLocalizedString("RELOAD_DATA",comment:"I'm in danger, I'm currently at  "), image: UIImage(named: "Icon"), backgroundColor: UIColor(red:52.00/255.0, green:152.00/255.0, blue:219.00/255.0, alpha:0.89))
    banner.dismissesOnTap = true
    banner.show(duration: 10.0)
    dispatch_async(dispatch_get_main_queue()) {
        //Not working ....
        self.tabeview.reloadData()
    }
}

func titleForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! {
    let str = "Oups"
    let attrs = [NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)]
    return NSAttributedString(string: str, attributes: attrs)
}

func descriptionForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! {
    let str = NSLocalizedString("NO_FRIENDS_TO_SHOW",comment:"No friends to show  ")
    let attrs = [NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleBody)]
    return NSAttributedString(string: str, attributes: attrs)
}

func imageForEmptyDataSet(scrollView: UIScrollView!) -> UIImage! {
    return UIImage(named: "no-friends")
}

func buttonTitleForEmptyDataSet(scrollView: UIScrollView!, forState state: UIControlState) -> NSAttributedString! {
    let str = NSLocalizedString("ADD_FRIENDS",comment:"Add a friend  ")
    let attrs = [NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 19)!]
    return NSAttributedString(string: str, attributes: attrs)
}

func emptyDataSetDidTapButton(scrollView: UIScrollView!) {
    let alert = SCLAlertView()
    let txt = alert.addTextField("Friend's username")
    alert.addButton("Add") {
        if(txt.text=="")
        {
            let banner = Banner(title: NSLocalizedString("ERROR_NO",comment:"An error occured"), subtitle: NSLocalizedString("ERROR_NO_TEXT",comment:"I'm in danger, I'm currently at  "), image: UIImage(named: "Icon"), backgroundColor: UIColor(red:152.00/255.0, green:52.00/255.0, blue:52.00/255.0, alpha:0.89))
            banner.dismissesOnTap = true
            banner.show(duration: 10.0)
        }
        else
        {

            let defaults = NSUserDefaults.standardUserDefaults()
            let username = defaults.objectForKey("name") as! String
            let remove_friend_username = txt.text! as String

            Alamofire.request(.GET, "http://www.example.com/add_friends.php", parameters: ["key_id": "xxx","user_id": username,"friend_receive_id": remove_friend_username, "action": "add"])
                .response { request, response, data, error in
                    dispatch_async(dispatch_get_main_queue()) {
                        self.tabeview.reloadData()
                        //Not working
                    }
            }

        }
    }
    alert.showEdit("Add friend", subTitle: "You can add a friend by enter his username")
}

}

1 个答案:

答案 0 :(得分:1)

我相信你在这里错过了一点点朋友:)

问题1 为什么重新加载tableView不会显示新数据?

你的函数reload_data只是重新加载数据伙伴:)当你调用reload数据时,所有tableView委托都会调用section中的行数,section数和cellForRowAtIndexPath,但所有这些方法都会根据数据返回值您提供的来源并不是伙伴:)

因此,如果您更改数据源然后调用重新加载数据,它们将显示新数据:)但在您的reload_data函数中,您根本不会更改数据源:)只需在未更改的数据源上调用重新加载数据再次渲染tableView,即所有:)

你能做什么:)

你已经有了一个使用almofire获取新数据的方法:)只是调用它并在成功块中无论如何你正在重新加载tableView :)所以一切都会很好伙伴:)

@IBAction func reload_data(sender: UIButton) {
    let banner = Banner(title: NSLocalizedString("RELOAD_DATA_TITLE",comment:"I'm in danger, I'm currently at  "), subtitle: NSLocalizedString("RELOAD_DATA",comment:"I'm in danger, I'm currently at  "), image: UIImage(named: "Icon"), backgroundColor: UIColor(red:52.00/255.0, green:152.00/255.0, blue:219.00/255.0, alpha:0.89))
    banner.dismissesOnTap = true
    banner.show(duration: 10.0)
    self.getallrecords() //simply call this method this will anyhow will reload data on success :)
}

问题2 为什么我的tableView显示重复数据???

你的tableView总是显示其数据源中的数据:)如果你的tableView显示重复的单元格,这意味着你的数据源中有重复的条目:)

你正在处理数组,将来你可能会迁移到coredata :) 了解一件事,当您输入或添加数据源条目时,如果您不想显示重复项,则必须明确处理它。

我该怎么办?

从您的代码中我知道每个对象的信息(用户名)值是唯一的。所以在盲目地添加对textArray的响应之前,检查文本数组是否已包含该对象,如果是,则不要再添加它:)

基于上述假设并相信您正在使用swift 2.0

if let data = try NSJSONSerialization.JSONObjectWithData(dataweneed.dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSJSONReadingOptions.MutableContainers]) as? NSArray {
                                    for dd in data{
                                        var name : String = dd["danger"]! as! String
                                        self.reports_d = name
                                        let info : String = dd["username"]! as! String
                                        name = NSLocalizedString("SEND_ALERT_BEGIN",comment:"SEND_ALERT") + name + NSLocalizedString("ALERTS",comment:"ALERTS")
                                        print("ID is : \(name)")
                                        print("Username is : \(info)") 

                                        if  !self.textArray.contains(info){                                                                                      

                                        self.textArray.addObject(info)
                                        self.subArray.addObject(name)
                                        } 

                                    }
                                    self.tabeview.reloadData()
                                }

现在有很多代码,我想要一个更简单的解决方案:)

在添加新响应之前清除数组:)全部:)

if let data = try NSJSONSerialization.JSONObjectWithData(dataweneed.dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSJSONReadingOptions.MutableContainers]) as? NSArray {
                                self.textArray.removeAll()
                                self.subArray.removeAll() //clear the arrays and then re populate them thats all no duplicate data anymore :P
                                for dd in data{
                                    var name : String = dd["danger"]! as! String
                                    self.reports_d = name
                                    let info : String = dd["username"]! as! String
                                    name = NSLocalizedString("SEND_ALERT_BEGIN",comment:"SEND_ALERT") + name + NSLocalizedString("ALERTS",comment:"ALERTS")
                                    print("ID is : \(name)")
                                    print("Username is : \(info)") 
                                    self.textArray.addObject(info)
                                    self.subArray.addObject(name)
                                }
                                self.tabeview.reloadData()
                            }
相关问题