MPNowPlayingInfoCenter:从Url设置MPMediaItemArtwork的最佳方法是什么?

Dam*_*ito 5 objective-c artwork mpmediaitem avplayer mpnowplayinginfocenter

我发现设置MPNowPlayingInfoCenter的MPMediaItemArtwork的所有方法都使用本地图像.MPMediaItemArtwork*albumArt = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"myimage"];

但我需要从imageURL设置它

目前我用这个......

    UIImage *artworkImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.currentTrack.imageUrl]]];

    MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage: artworkImage];
    [self.payingInfoCenter setValue:albumArt forKey:MPMediaItemPropertyArtwork];
Run Code Online (Sandbox Code Playgroud)

任何的想法?

Dam*_*ito 6

这是我最好的解决方案:

- (void)updateControlCenterImage:(NSURL *)imageUrl
{       
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{

            NSMutableDictionary *songInfo = [NSMutableDictionary dictionary]; 
            UIImage *artworkImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];
            if(artworkImage)
            {
                MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage: artworkImage];
                [songInfo setValue:albumArt forKey:MPMediaItemPropertyArtwork];
            }
           MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter];
          infoCenter.nowPlayingInfo = songInfo; 
    });
}
Run Code Online (Sandbox Code Playgroud)

/!\如果你已经设置了MPNowPlayingInfoCenter,那么它将被覆盖,或者所有其他值都将被覆盖


Nic*_*kDK 5

let mpic = MPNowPlayingInfoCenter.default()
DispatchQueue.global().async {

            if let urlString = yourUrlString, let url = URL(string:urlString)  {
                if let data = try? Data.init(contentsOf: url), let image = UIImage(data: data) {

                    let artwork = MPMediaItemArtwork(boundsSize: image.size, requestHandler: { (_ size : CGSize) -> UIImage in

                        return image

                    })


                    DispatchQueue.main.async {
                        mpic.nowPlayingInfo = [
                            MPMediaItemPropertyTitle:"Title",
                            MPMediaItemPropertyArtist:"Artist",
                            MPMediaItemPropertyArtwork:artwork
                        ]
                    }
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

这在 iOS 11、swift 4 中对我有用