Search code examples
iosswiftavplayeravplayeritem

Swift: cannot subscript value of [String:NSObject] with index of type?


Ok, I am working with MPMediaItems here and I need to get an image from an MPMediaItemArtwork. Problem is since Im using another framework, this imageWithSize in Swift3 is not working for me. My MPMediaItem seems to be in a different format:

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

Nothing is printed and I get error:

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

What does this mean? How can I get the image into a UIImage from here?

Within the framework, the guy has:

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)
        }
    }

Solution

  • The nowPlayingInfo dictionary is declared as [String:NSObject] so you clearly you need to use a String as a key.

    But you are trying to use things like MPMediaItemArtwork which is a class name.

    The list of valid keys can be found by reading the Overview for the MPNowPlayingInfoCenter class (which is where nowPlayingInfo is declared). As you can see, the keys can be found from the MPMediaItem documentation.

    So you need to replace MPMediaItemArtwork with MPMediaItemPropertyArtwork.