I'm making a music play app on Swift, which one could upload music from computer's web browser(GCD WebUploader) into the app's document dir. Now I could show all songs in table View and also the search bar is working correctly.
But I get issues when implement delete func. Ok, 2 questions.
1) when I swipe to delete a row from table view, then I could see that row is disappeared. But when I force this app and re-launch it then the deleted one is still there. -> Do I need to use async for all funcs or some database? I hit the wall and need help.
2) when I swipe to delete a row from search bar, the one is deleted from search bar, but when switch back, that song is still in the table view.
/// SongData.swift is using to store song's metaData.
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
}
}
/// Table View Controller including the search bar
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()
}
}
}
Conform SongData
to Equatable
as below,
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
}
}
Now remove the songData
object from the tableData
while searching as below,
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)")
}
}
}