6

All methods I found to set MPMediaItemArtwork of MPNowPlayingInfoCenter are with local images. MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage: [UIImage imageNamed:@"myimage"];

But I need to set this from an imageURL

Currently i use this...

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

    MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage: artworkImage];
    [self.payingInfoCenter setValue:albumArt forKey:MPMediaItemPropertyArtwork];

Any idea?

4

2 回答 2

7

这是我最好的解决方案:

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

/!\ 如果你已经设置了MPNowPlayingInfoCenter,获取它,否则所有其他值将被覆盖

于 2015-03-16T10:03:34.670 回答
4
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
                        ]
                    }
                }
            }
        }

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

于 2017-10-24T17:58:39.920 回答