swift - 从 'table view' 和 'filtered search bar' 删除行不起作用

标签 swift tableview searchbar swift5

我正在 Swift 上制作一个音乐播放应用程序,它可以将音乐从计算机的网络浏览器(GCD WebUploader)上传到应用程序的文档目录中。现在我可以在表格 View 中显示所有歌曲,并且搜索栏也可以正常工作。

但是我在实现删除功能时遇到问题。好的,有 2 个问题。

1)当我滑动从 TableView 中删除一行时,我可以看到该行消失了。但是,当我强制该应用程序并重新启动它时,已删除的应用程序仍然存在。 -> 我需要对所有函数或某些数据库使用异步吗?我碰壁了,需要帮助。

2)当我从搜索栏中滑动删除一行时,该行将从搜索栏中删除,但是当切换回来时,该歌曲仍然在表格 View 中。

enter image description here

///SongData.swift 用于存储歌曲的元数据。

import Foundation
import UIKit

class SongData {
    var songName: String?
    var artistName: String?
    var albumName: String?
    var albumArtwork: UIImage?
    var url: URL?

    init(songName: String, artistName: String, albumName: String, albumArtwork: UIImage, url: URL) {
        self.songName = songName
        self.artistName = artistName
        self.albumName = albumName
        self.albumArtwork = albumArtwork
        self.url = url
    }

}

///包含搜索栏的 TableView Controller

import UIKit
import AVKit
import AVFoundation


class SongsTableViewController: UITableViewController, UISearchResultsUpdating{

    var directoryContents = [URL]()
    var songName: String?
    var artistName: String?
    var albumName: String?
    var albumArtwork: UIImage?

    var audioPlayer: AVAudioPlayer!
    var resultSearchController = UISearchController()

    // create type SongData array to store song's metaData.
    var tableData = [SongData]()
    var filteredTableData = [SongData]()

    override func viewDidLoad() {
        super.viewDidLoad()

        do {

            // Get the document directory url
            let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

            // Get the directory contents urls (including subfolders urls)
            directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)

            // if you want to filter the directory contents you can do like this:
            let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" }

            // get music metadata (artist, album...)
            for url in mp3Files {
                let asset = AVAsset(url: url)
                let metaData = asset.metadata

                if let songTitle = metaData.first(where: {$0.commonKey == .commonKeyTitle}), let value = songTitle.value as? String {
                    songName = value
                } else {
                    songName = "No song name"
                }

                if let artist = metaData.first(where: {$0.commonKey == .commonKeyArtist}), let value = artist.value as? String {
                    artistName = value
                } else {
                    artistName = "No artist name"
                }

                if let album = metaData.first(where: {$0.commonKey == .commonKeyAlbumName}), let value = album.value as? String {
                    albumName = value
                } else {
                    albumName = "No album name"
                }

                if let albumImage = metaData.first(where: {$0.commonKey == .commonKeyArtwork}), let value = albumImage.value as? Data {
                    albumArtwork = UIImage(data: value)
                } else {
                    albumArtwork = UIImage(named: "Apple")
                    print("artWork is not found!")
                }

                tableData.append(SongData(songName: songName!, artistName: artistName!, albumName: albumName!, albumArtwork: albumArtwork!, url: url))
            }

        } catch {
            print(error)
        }

        // add search bar
        resultSearchController = ({
            let controller = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.dimsBackgroundDuringPresentation = false
            controller.searchBar.sizeToFit()

            self.tableView.tableHeaderView = controller.searchBar

            return controller
            })()

        // reload the table
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if resultSearchController.isActive {
            return filteredTableData.count
        } else {
            return tableData.count
        }

    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)

        if resultSearchController.isActive {
            cell.textLabel?.text = filteredTableData[indexPath.row].songName
            cell.detailTextLabel?.text = filteredTableData[indexPath.row].artistName
            cell.imageView?.image = filteredTableData[indexPath.row].albumArtwork
            return cell
        } else {
            cell.textLabel?.text = tableData[indexPath.row].songName
            cell.detailTextLabel?.text = tableData[indexPath.row].artistName
            cell.imageView?.image = tableData[indexPath.row].albumArtwork
            return cell
        }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if resultSearchController.isActive {
            do {
                // this part is not started yet
                try audioPlayer = AVAudioPlayer(contentsOf: filteredTableData[indexPath.row].url!)
                audioPlayer.prepareToPlay()
                audioPlayer.play()
            } catch {
                print("could not load file")
            }
        } else {
            do {
                try audioPlayer = AVAudioPlayer(contentsOf: directoryContents[indexPath.row])
                audioPlayer.prepareToPlay()
                audioPlayer.play()
            } catch {
                print("could not load file")
            }
        }
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCell.EditingStyle.delete {
            if resultSearchController.isActive {
                filteredTableData.remove(at: indexPath.row)
                tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
            } else {
                tableData.remove(at: indexPath.row)
                tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
                // remove data from local source
                try! FileManager.default.removeItem(at: directoryContents[indexPath.row])
                print("delete song at index \(indexPath.row)")
            }
        }
    }

    func updateSearchResults(for searchController: UISearchController) {
        filteredTableData.removeAll(keepingCapacity: false)

        let searchText = searchController.searchBar.text!
        for item in tableData {
            let str = item.songName
            if str!.lowercased().contains(searchText.lowercased()) {
                filteredTableData.append(item)
            }
        }

        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }
}

最佳答案

使SongData符合Equatable,如下所示,

class SongData: Equatable {

    static func == (lhs: SongData, rhs: SongData) -> Bool {
        return lhs.songName == rhs.songName &&
                lhs.artistName == rhs.artistName &&
                lhs.albumName == rhs.albumName &&
                lhs.albumArtwork == rhs.albumArtwork
    }

    var songName: String?
    var artistName: String?
    var albumName: String?
    var albumArtwork: UIImage?
    var url: URL?

    init(songName: String, artistName: String, albumName: String, albumArtwork: UIImage, url: URL) {
        self.songName = songName
        self.artistName = artistName
        self.albumName = albumName
        self.albumArtwork = albumArtwork
        self.url = url
    }
}

现在,在搜索时从 tableData 中删除 songData 对象,如下所示,

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCell.EditingStyle.delete {
        if resultSearchController.isActive {
            let song = filteredTableData[indexPath.row]
            if let index = tableData.firstIndex(of: song) {
                try! FileManager.default.removeItem(at: directoryContents[index])
                tableData.remove(at: index)
            }

            filteredTableData.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
        } else {
            tableData.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
            // remove data from local source
            try! FileManager.default.removeItem(at: directoryContents[indexPath.row])
            print("delete song at index \(indexPath.row)")
        }
    }
}

关于swift - 从 'table view' 和 'filtered search bar' 删除行不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57706899/

相关文章:

iphone - 我如何测试某个表格 View 单元格是否具有特定图像?

css - 单击外部按钮扩展搜索栏

ios - 有时在 Xcode (Swift) 中,应用程序会因滑动删除操作而崩溃

Swift - 编译器警告我没有解包一个可选的但然后强制我解包使用!而不是?

ios - 如何使用搜索栏使用 swift 从 json 结果中获取数据?

ios - 在 Swift 2.x 和 iOS9 中以编程方式关闭 searchBar

ios - 如何使用相同的工具栏按钮显示/隐藏搜索栏

swift - 部分索引更改时 NSFetchedResultsController 崩溃

InterfaceBuilder 中带有自定义 accessoryView 的 iOS UITableViewCell

Swift,防止 uitableviewcell 重用