gpt4 book ai didi

swift - Swift 访问 URL 路径时删除部分字符串

转载 作者:行者123 更新时间:2023-11-28 07:49:19 28 4
gpt4 key购买 nike

我目前正在尝试在路径中创建歌曲列表“/Music/Itunes/iTunes Media/Music” 最终将它们插入到 Youtube API 中。我可以访问所有需要的文件。我只是在寻找一种清理打印项目的方法,如下所示,专辑名称位于歌曲名称的前面。

var test = try FileManager.default.subpathsOfDirectory (atPath: completePath)

let list = test.joined(separator: "\n")
// Attempt to delete album name
print(list.replacingOccurrences(of: "/\(String())/" , with: ""))

这打印

J. Cole/2014 Forest Hills Drive
J. Cole/2014 Forest Hills Drive/12 Love Yourz.mp3
J. Cole/2014 Forest Hills Drive/06 Fire Squad.mp3
J. Cole/2014 Forest Hills Drive/09 No Role Modelz.mp3

有没有办法删除那部分?为了返回示例“J. Cole 12 Love Yourz.mp3”

最佳答案

在 Swift 中,您应该使用 URL 而不是路径来引用文件。因此,不要使用 subpathsOfDirectory,而是使用 FileManagerenumerator(at:includingPropertiesForKeys:options:errorHandler:)。此方法返回的枚举器将为目录中的每个子路径提供一个 URL。不幸的是,DirectoryEnumerator 在其接口(interface)中有点 Objective-C-ish,这意味着它的元素是 Any 而不是您期望的 URL ,但您仍然可以像这样访问它的 URL:

for each in enumerator {
guard let eachURL = each as? URL, eachURL.pathExtension == "mp3" else { continue }

let trackName = eachURL.lastPathComponent
let albumName = eachURL.deletingLastPathComponent().deletingLastPathComponent().lastPathComponent

print("\(albumName) \(trackName)")
}

然后,您可以只使用 URLlastPathComponent 属性来获取文件名,而不获取其余路径。对代表专辑的目录做同样的事情,你可以将专辑名称和轨道名称拼接起来得到你想要的。

关于swift - Swift 访问 URL 路径时删除部分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50109290/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com