如何理解一个播放列表是一个可编辑的MusicKit?(iOS 16)

42fyovps  于 2023-03-05  发布在  iOS
关注(0)|答案(1)|浏览(133)

我怎样才能只检索可编辑的播放列表?或者换句话说,我怎样才能检索只由用户创建的播放列表?
我们可以通过以下代码块获取用户的播放列表:

var request = MusicLibraryRequest<Playlist>()

 request.sort(by: \.lastPlayedDate, ascending: false)

 let response = try await request.response()

此外,我们还可以使用以下代码块向播放列表中添加曲目:

TASK {
     do {
         try await MusicLibrary.shared.add(track, to: playlist)
      } catch (let error) {
         print(error)
     }
}

但是,并非所有播放列表都是可编辑的。例如,如果播放列表是由Apple或其他Apple Music用户创建的,我们在向播放列表添加曲目时会收到错误消息,因为我们没有权限执行此操作。
我收到以下错误:错误域= MPErrorDomain代码= 5 "不支持请求的操作"用户信息= {NSLocalizedDescription =不支持请求的操作}

qojgxg4l

qojgxg4l1#

我还没有弄清楚如何使用新的MusicLibraryRequest,所以我写了自己的实现。希望它能有所帮助。
第一步是创建一个具有canEdit属性的MLibraryPlaylist,因为这正是您想要的:

import Foundation
import MusicKit

public struct MLibraryPlaylist: Codable, MusicItem {
  public let id: MusicItemID
  public let attributes: Attributes

  public struct Attributes: Codable, Sendable {
    public let canEdit: Bool
    public let name: String
    public let isPublic: Bool
    public let hasCatalog: Bool
    public let playParams: PlayParameters
    public let description: Description?
    public let artwork: Artwork?
  }

  public struct Description: Codable, Sendable {
    public let standard: String
  }

  public struct PlayParameters: Codable, Sendable {
    public let id: MusicItemID
    public let isLibrary: Bool
    public let globalID: MusicItemID?

    enum CodingKeys: String, CodingKey {
      case id, isLibrary
      case globalID = "globalId"
    }
  }

  public var globalID: String? {
    attributes.playParams.globalID?.rawValue
  }
}

然后,使用Apple Music API获取媒体库播放列表,并将数据解码为MLibraryPlaylist(而非Playlist)的集合:

public typealias LibraryPlaylists = MusicItemCollection<LibraryPlaylist>

let libraryPlaylistsURL = URL(string: "https://api.music.apple.com/v1/me/library/playlists")

guard let libraryPlaylistsURL else { return }

let request = MusicDataRequest(urlRequest: URLRequest(url: libraryPlaylistsURL))
let response = try await request.response()
let playlists = try JSONDecoder().decode(LibraryPlaylists.self, from: response.data)

guard let playlist = playlists.first else { return }

print(playlist)
print(playlist.attributes.canEdit)

我希望它能解决你的问题!我知道它不如原生实现,在那里你也可以按上次播放日期过滤。

相关问题