Swift:无法弄清楚如何保存用户离开tableview的方式

时间:2017-06-08 22:19:30

标签: ios swift uitableview core-data nsuserdefaults

使用Swift 3

我已经在博客阅读器应用程序上工作了一段时间,但我一直坚持如何保存tableview,就像用户如何离开它一样。

该应用程序通过我将数据输入到mysql数据库中,该数据库使用php发送并通过json和swift 3接收以填充tableview。我希望每天更新这个数据库。 tableview中有两个部分,一个是followArray,第二个是mainArray,它是jsonArray之后的所有对象。当用户单击“关注”按钮时,该单个单元格将移动到followArray,用户可以在其中看到正在更新的博客并接收通知。

我尝试通过将整个数组保存到一个对象中来使用UserDefaults,但它没有用,因为它是使用NSCoding复杂创建NSData对象的方法,当不需要保存整个数组时(我的猜测) )。

我的问题是,有一种简单的方法可以保存用户离开桌面视图的方式吗?

例如:在'所有对象部分'中假设我有3个单元格并且用户单击2个单元格上的跟随按钮,这2个单元格现在位于“所有对象部分”中的1个单元格的“后续部分”中。如何保存此tableview的状态。我想保存当前跟随单元格的哪个部分和更改的按钮,现在是一个跟随按钮而不是跟随按钮(保存隐藏的启用代码,因为我隐藏一个按钮以显示另一个)。

我是否使用UserDefaults或CoreData?也许是CocoaPod库?我是保存整个数组还是保存它的哪个部分和.hidden代码?更新和添加新对象将如何影响它?

我对Swift相当新,所以如果你能提供帮助,我们将不胜感激。您需要了解应用程序如何工作的任何代码,只需要它,因为我不知道需要显示什么代码。我知道你不应该要求代码,但是如果可以的话,那将是很好的,因为我已经尝试了几个月而没有任何进展。谢谢!

以下是处理传入json数据的方法:

MainController.swift

var jsonArray: NSMutableArray = []
var mainArray = [Blog]()
var followedArray = [Blog]()
var filteredArray = [Blog]()

// Title for Header
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    if !(searchController.isActive && searchController.searchBar.text != "") {

        if section == 0 {
            return "Followed Blogs"
        }
        else {
            return "All Blogs"
        }
    }
    return "Filtered Blogs"
}

// Number of Rows in Section
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if !(searchController.isActive && searchController.searchBar.text != "") {

        if section == 0 {

            return followedArray.count
        }
        else if (section == 1) {

            return mainArray.count
        }

    }
    return filteredArray.count

}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let CellIdentifier = "Cell"
    var cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier) as! CustomCell

    if cell != cell {
        cell = CustomCell(style: UITableViewCellStyle.default, reuseIdentifier: CellIdentifier)
    }

    // Configuring the cell
    var blogObject: Blog

    if !(searchController.isActive && searchController.searchBar.text != "") {
        if indexPath.section == 0 {
            blogObject = followedArray[indexPath.row] 
            cell.populateCell(blogObject, isFollowed: true, indexPath: indexPath, parentView: self)
        }
        else if indexPath.section == 1 {
            blogObject = mainArray[indexPath.row] 
            cell.populateCell(blogObject, isFollowed: false, indexPath: indexPath, parentView: self)
        }
    }
    else {
        blogObject = filteredArray[indexPath.row] 
        cell.populateCell(blogObject, isFollowed: false, indexPath: indexPath, parentView: self)
    }

    return cell
}

@IBAction func followButtonClick(_ sender: UIButton!) {

    // Adding row to tag
    let buttonPosition = (sender as AnyObject).convert(CGPoint.zero, to: self.myTableView)
    if let indexPath = self.myTableView.indexPathForRow(at: buttonPosition) {

        // Showing Status Labels
        let cell = self.myTableView.cellForRow(at: indexPath) as! CustomCell
        cell.firstStatusLabel.isHidden = false
        cell.secondStatusLabel.isHidden = false

        // Change Follow to Following
        (sender as UIButton).setImage(UIImage(named: "follow.png")!, for: .normal)
        cell.followButton.isHidden = true
        cell.followedButton.isHidden = false

        // Checking wether to import from mainArray or filteredArray to followedArray
        if !(searchController.isActive && searchController.searchBar.text != "") {

            self.myTableView.beginUpdates()

            // ----- Inserting Cell to followedArray -----
            followedArray.insert(mainArray[indexPath.row], at: 0)
            myTableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .fade)

            // ----- Removing Cell from mainArray -----
            mainArray.remove(at: indexPath.row)
            let rowToRemove = indexPath.row
            self.myTableView.deleteRows(at: [IndexPath(row: rowToRemove, section: 1)], with: .fade)

            self.myTableView.endUpdates()

            myTableView.reloadData()
        }
        else {

            self.myTableView.beginUpdates()

            // ----- Inserting Cell to followedArray -----
            let blogObject: Blog = filteredArray[indexPath.row]
            let indexOfObjectInArray = mainArray.index(of: blogObject)

            followedArray.insert(blogObject, at: 0)

            // ----- Removing Cell from filteredArray -----
            filteredArray.remove(at: indexPath.row)
            blogArray.remove(at: indexOfObjectInArray!)
            let rowToRemove = indexPath.row
            self.myTableView.deleteRows(at: [IndexPath(row: rowToRemove, section: 0)], with: .fade)

            self.myTableView.endUpdates()

            myTableView.reloadData()
        }
    }
}

func retrieveDataFromServer() {

    let getDataURL = "http://exampleblog.com/receiving.php"
    let url: NSURL = NSURL(string: getDataURL)!

    do {

        let data: Data = try Data(contentsOf: url as URL)
        jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSMutableArray

        // Looping through jsonArray
        for i in 0..<jsonArray.count {

            // Create Blog Object
            let bID: String = (jsonArray[i] as AnyObject).object(forKey: "id") as! String
            let bName: String = (jsonArray[i] as AnyObject).object(forKey: "blogName") as! String
            let bStatus1: String = (jsonArray[i] as AnyObject).object(forKey: "blogStatus1") as! String
            let bStatus2: String = (jsonArray[i] as AnyObject).object(forKey: "blogStatus2") as! String
            let bURL: String = (jsonArray[i] as AnyObject).object(forKey: "blogURL") as! String
            // New
            let bType: String = (jsonArray[i] as AnyObject).object(forKey: "blogType") as! String
            let bDate: String = (jsonArray[i] as AnyObject).object(forKey: "blogDate") as! String
            let bPop: String = (jsonArray[i] as AnyObject).object(forKey: "blogPop") as! String

            // Add Blog Objects to mainArray
            mainArray.append(Blog(blogName: bName, andBlogStatus1: bStatus1, andBlogStatus2: bStatus2, andBlogURL: bURL, andBlogID: bID, andBlogType: bType, andBlogDate: bDate, andBlogPop: bPop))

        }
    }
    catch {
        print("Error: (Retrieving Data)")
    }

    myTableView.reloadData()
}

CustomCell.swift - 如何填充单元格enter code here

class CustomCell: UITableViewCell {

@IBOutlet weak var firstStatusLabel: UILabel!
@IBOutlet weak var secondStatusLabel: UILabel!
@IBOutlet weak var followButton: UIButton!
@IBOutlet weak var followedButton: UIButton!

override func awakeFromNib() {
    super.awakeFromNib()

    self.followButton.isHidden = true
    self.followedButton.isHidden = true
}

func populateCell(_ blogObject: Blog, isFollowed: Bool, indexPath: IndexPath, parentView: Any) {

    // Loading Status Labels
    self.firstStatusLabel.text = blogObject.blogStatus1
    self.secondStatusLabel.text = blogObject.blogStatus2
    self.firstStatusLabel.isHidden = true
    self.secondStatusLabel.isHidden = true

    if isFollowed {
        self.followedButton.tag = indexPath.row
        self.followedButton.addTarget(parentView, action: #selector(MainController.followedButtonClick(_:)), for: .touchUpInside)

        self.followedButton.isHidden = false
        self.followButton.isHidden = true

        // Status Labels
        self.firstStatusLabel.isHidden = false
        self.secondStatusLabel.isHidden = false

    }
    else {
        self.followButton.tag = indexPath.row
        self.followButton.addTarget(parentView, action: #selector(MainController.followButtonClick(_:)), for: .touchUpInside)

        self.followedButton.isHidden = true
        self.followButton.isHidden = false

        // Status Labels
        self.firstStatusLabel.isHidden = true
        self.secondStatusLabel.isHidden = true

    }
}
}

Blog.swift

class Blog: NSObject {

// Strings
var blogName: String?
var blogStatus1: String?
var blogStatus2: String?
var blogURL: String?
var blogID: String?
var blogType: String?
var blogDate: String?
var blogPop: String?

override init() {

}

// Converting Strings into Objects
init(blogName bName: String,
     andBlogStatus1 bStatus1: String,
     andBlogStatus2 bStatus2: String,
     andBlogURL bURL: String,
     andBlogID bID: String,
     andBlogType bType: String,
     andBlogDate bDate: String,
     andBlogPop bPop: String)
{
    super.init()

    self.blogName = bName
    self.blogStatus1 = bStatus1
    self.blogStatus2 = bStatus2
    self.blogURL = bURL
    self.blogID = bID
    self.blogType = bType
    self.blogDate = bDate
    self.blogPop = bPop
}

}

1 个答案:

答案 0 :(得分:1)

有许多不同的方法可以实现您想要的,无论是本地还是远程存储信息。如果博客ID是唯一的,您可以将它们作为字符串数组存储在默认值中:

UserDefaults.standard.set(followedBlogIds, forKey: "followedBlogIds")

然后你可以随时抓住它们,只需确保正确打开/投射它们:

if let storedBlogIds = UserDefaults.standard.object(forKey: "followedBlogIds") as? [String] {
    //filter your blogs by id and put them in the appropriate
    //arrays for your table
}