简体   繁体   English

Swift 5.2 中的 iTunes 库框架

[英]ITunes Library Framework in Swift 5.2

I have searched everywhere and I am unable to find a swifty example of how to use the Apple ITunesLibraryFramework.我到处搜索,但找不到如何使用 Apple ITunesLibraryFramework 的快速示例。 I have been trying to figure out how to use this Framework in Swift 5.2.我一直试图弄清楚如何在 Swift 5.2 中使用这个框架。

I want to get information directly from the Music library rather than having to rely on a XML library export file.我想直接从音乐库中获取信息,而不必依赖 XML 库导出文件。

I have the below code in my playground and it prints nothing legible.我的操场上有以下代码,它打印的内容不清晰。 How would I access the fields for playlists and mediaItems and be able to read them in human readable form?我将如何访问播放列表和 mediaItems 的字段并能够以人类可读的形式阅读它们?

I have installed the framework in the project.我已经在项目中安装了框架。 This is my project playground code:这是我的项目游乐场代码:

import Foundation
import iTunesLibrary

var library:ITLibrary

do {
    let library = try ITLibrary(apiVersion: "1.1")
    let mediaItems = library.allMediaItems
    let playlists = library.allPlaylists
    print("Media Folder Location - \(String(describing: library.mediaFolderLocation))")
    print("\nPlaylists - \(playlists)")
    print("\nTracks - \(mediaItems)")
} catch let error as NSError {
    print(error)
}

This is the ITLibrary.m file that I imported the header:这是我导入 header 的 ITLibrary.m 文件:

#import <Foundation/Foundation.h>
#import <iTunesLibrary/iTunesLibrary.h>

When I run the above code in the project playground all I get is a bunch of binary data for both playlists and mediaItems.当我在项目操场上运行上述代码时,我得到的只是播放列表和 mediaItems 的一堆二进制数据。 All I want to do is iterate over the data and collect information from the library for use in my program.我要做的就是遍历数据并从库中收集信息以用于我的程序。 It's probably something easy, but I haven't found it yet.这可能很容易,但我还没有找到它。

EDIT: - After using @Vincent's answer I ran into another problem with the following code:编辑: - 使用@Vincent的回答后,我遇到了以下代码的另一个问题:

import Foundation
import iTunesLibrary

let library = try ITLibrary(apiVersion: "1.1")
typealias tracks = [NSNumber:TrackInfo]
var trackInfo = TrackInfo()

struct TrackInfo {
    var title = ""
    var artist = ""
    var album = ""
    var totalTime = 0
    var year = 0
    var persistentID = ""
    var location:URL!
}

let songs = library.allMediaItems
let playlists = library.allPlaylists

for playlist in playlists {
    if playlist.name.lowercased().contains("test-") {
        print("New Playlist---------------\nName: \(playlist.name)")
        for song in playlist.items {
            trackInfo.title = song.title
            print("\n\nNew Track-----------------\nTitle: \(trackInfo.title)")
            if song.artist?.name != nil {
                trackInfo.artist = song.artist?.name as! String
            }
            print("Artist: \(trackInfo.artist)")
            trackInfo.album = song.album.title!
            print("Albumn Name: \(trackInfo.album)")
            trackInfo.totalTime = song.totalTime
            print("Total Time: \(trackInfo.totalTime)")
            trackInfo.year = song.year
            print("Year: \(trackInfo.year)")
            trackInfo.location = song.location!
            print("Location: \(trackInfo.location!)")
            var persistentID = song.persistentID
            tracks.updateValue(song.persistentID, trackInfo)
        }
    }
}

The issue I'm having is getting the tracks info into the trackInfo dictionary.我遇到的问题是将曲目信息放入 trackInfo 字典。 I'm trying to use the track persistentID (NSNumber) as the key for the dictionary, which I have declared.我正在尝试使用 track persistentID (NSNumber) 作为我已声明的字典的键。 For some reason it isn't allowing me to use it.出于某种原因,它不允许我使用它。

Here's how you can have it print each playlist and track:以下是如何让它打印每个播放列表和曲目:

Each ITLibPlaylist or ITLibMediaItem object contains many information about each playlist/media item.每个ITLibPlaylistITLibMediaItem object 都包含有关每个播放列表/媒体项目的许多信息。 To get only the name/title of each, you will have to iterate through the results to retrieve them.要仅获取每个名称/标题,您必须遍历结果以检索它们。

For this example below, the name of each playlist's name is printed.对于下面的这个例子,每个播放列表的名字都会被打印出来。

    print("\nPlaylists -")
    for playlist in playlists {
        print(playlist.name)
    }

Which will print (for example):将打印(例如):

Playlists -
Library
Music

For this example below, the name of each track's name is printed.对于下面的这个例子,每个轨道的名字都会被打印出来。

    print("\nTracks -")
    for mediaItem in mediaItems {
        print(mediaItem.title)
    }

Which will print (for example):将打印(例如):

Tracks -
Ev'ry Time We Say Goodbye
My Favorite Things
But Not for Me
Summertime

Edit : Here's the secondary solution to the secondary problem:编辑:这是次要问题的次要解决方案:

First things first, a dictionary should be initialised, instead of using typealias .首先,应该初始化字典,而不是使用typealias

typealias only makes an alias for a pre existing type, like typealias只为预先存在的类型创建别名,例如

typealias NumberWithAlotOfDecimals = Double
let a: NumberWithAlotOfDecimals = 10.1
let b: Double = 10.1

both will a and b are Double , as NumberWithAlotOfDecimals is just an alias for Double . ab都是Double ,因为NumberWithAlotOfDecimals只是Double的别名。

Here's how to initialise:以下是初始化方法:

//typealias tracks = [NSNumber:TrackInfo] // not this
var tracks = [NSNumber:TrackInfo]() // but this

Secondly, nullable objects should be properly handled其次,应妥善处理可空对象

            if let artistName = song.artist?.name {
                trackInfo.artist = artistName
            }

and

            if let title = song.album.title {
                trackInfo.album = title
            }
            if let location = song.location {
                trackInfo.location = location
                print("Location: \(location)")
            }

instead of代替

            if song.artist?.name != nil {
                trackInfo.artist = song.artist?.name as! String
            }

Please do not use !请不要使用! to force unwrap nullable objects as that will cause runtime crashes when the object is nil .强制解包可空对象,因为当 object 为nil时,这将导致运行时崩溃。

Lastly, this is the way to store key value into dictionary in Swift.最后,这是在 Swift 中将键值存储到字典中的方法。

            let persistentID = song.persistentID
            //tracks.updateValue(song.persistentID, trackInfo) // not this
            tracks[persistentID] = trackInfo // this 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM