简体   繁体   English

MPMediaItem的发布日期返回Nil(迅速4)

[英]Release Date of MPMediaItem returning Nil (Swift 4)

I am trying to get the realease year of songs in a music player but all I am getting is nil values returned. 我正在尝试获取音乐播放器中歌曲的发行年份,但我得到的只是返回的零值。 I've tried writing it every way I can think of and it always returns nil. 我尝试过用我能想到的所有方式编写它,但它始终返回nil。 I've found very little help on this except that it seems this is a known problem... This is the one resource I found that looks like it might help: Get album year for item in iPod library? 除了这似乎是一个已知的问题外,我对此几乎没有帮助。这是我发现的一种资源,它看起来可能会有所帮助: 在iPod库中获取专辑的年份? but I believe this is objective C. My question is this. 但是我相信这是客观的C。我的问题是这个。 Does anyone know how to get the release date of MPMediaItems in Swift code? 有谁知道如何在Swift代码中获取MPMediaItems的发布日期? Or know how to translate the linked article to Swift language for me to try. 或者知道如何将链接的文章翻译为Swift语言,以供我尝试。 Thanks a bunch! 谢谢一群!

func getYear() {
    let mediaQuery = MPMediaQuery.songs()
    for songs in mediaQuery.items! {
        print(songs.title)
        print(songs.releaseDate)
        print(((songs.value(forProperty: MPMediaItemPropertyReleaseDate)!))
        print(songs.getReleaseDate())
    }
}

extension MPMediaItem {
    @available(iOS 10.0, *)
    func getReleaseDate() -> Date? {
        return self.perform(#selector(getter: MPMediaItem.releaseDate))?.takeUnretainedValue() as! NSDate? as Date?
    }
}

I had the same problem and thanks to the resource you linked, I managed to solve it! 我遇到了同样的问题,由于您链接的资源,我设法解决了它! I translated the Objective-C code to Swift 4 and it just works like a charm even on iOS 11 with Xcode 9, here's the code: 我将Objective-C代码翻译为Swift 4,即使在带有Xcode 9的iOS 11上,它也可以像魅力一样工作,这是代码:

let yearNumber: NSNumber = item.value(forProperty: "year") as! NSNumber
if (yearNumber.isKind(of: NSNumber.self)) {
    let year = yearNumber.intValue
    if (year != 0) {
               // do something with year
    }
}

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

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