Swift:不能下标[String:NSObject]的索引类型值?

时间:2017-06-21 17:41:25

标签: ios swift avplayer avplayeritem

好的,我在这里使用MPMediaItems,我需要从MPMediaItemArtwork获取图像。问题是因为我使用另一个框架,这个imageWithSize in Swift3对我不起作用。我的MPMediaItem似乎采用不同的格式:

 if let artWork = AudioPlayerManager.shared.currentTrack?.nowPlayingInfo?[MPMediaItemArtwork] as? MPMediaItemArtwork {
            trackImg = artWork.image(at: CGSize(width: 300, height: 300))!
            print("IMG: ",trackImg)
        }

什么都没打印,我收到错误:

cannot subscript value of [String:NSObject] with index of type MPMediaItemArtwork.Type

这是什么意思?如何从这里将图像变成UIImage?

在这个框架内,这家伙有:

fileprivate func extractMetadata() {
        Log("Extracting meta data of player item with url: \(url)")
        for metadataItem in (self.playerItem?.asset.commonMetadata ?? []) {
            if let _key = metadataItem.commonKey {
                switch _key {
                case AVMetadataCommonKeyTitle       : self.nowPlayingInfo?[MPMediaItemPropertyTitle] = metadataItem.stringValue as NSObject?
                case AVMetadataCommonKeyAlbumName   : self.nowPlayingInfo?[MPMediaItemPropertyAlbumTitle] = metadataItem.stringValue as NSObject?
                case AVMetadataCommonKeyArtist      : self.nowPlayingInfo?[MPMediaItemPropertyArtist] = metadataItem.stringValue as NSObject?
                case AVMetadataCommonKeyArtwork     :
                    if
                        let _data = metadataItem.dataValue,
                        let _image = UIImage(data: _data) {
                            self.nowPlayingInfo?[MPMediaItemPropertyArtwork] = self.mediaItemArtwork(from: _image)
                    }
                default                             : continue
                }
            }
        }
        // Inform the player about the updated meta data
        AudioPlayerManager.shared.didUpdateMetadata()
    }

    fileprivate func mediaItemArtwork(from image: UIImage) -> MPMediaItemArtwork {
        if #available(iOS 10.0, *) {
            return MPMediaItemArtwork.init(boundsSize: image.size, requestHandler: { (size: CGSize) -> UIImage in
                return image
            })
        } else {
            return MPMediaItemArtwork(image: image)
        }
    }

1 个答案:

答案 0 :(得分:1)

nowPlayingInfo字典被声明为[String:NSObject],因此您显然需要使用String作为密钥。

但您正在尝试使用类似MPMediaItemArtwork的内容。

可以通过阅读MPNowPlayingInfoCenter类的概述(这是声明nowPlayingInfo的位置)找到有效密钥列表。如您所见,可以从MPMediaItem文档中找到密钥。

因此,您需要将MPMediaItemArtwork替换为MPMediaItemPropertyArtwork