Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MPNowPlayingInfoCenter : What is the best way to set MPMediaItemArtwork from an Url?

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?

like image 611
Damien Romito Avatar asked Jun 09 '14 23:06

Damien Romito


2 Answers

That's my best solution:

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

/!\ if you've already setted the MPNowPlayingInfoCenter , get it or all other values will be overridden

like image 107
Damien Romito Avatar answered Nov 06 '22 12:11

Damien Romito


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

That worked for me in iOS 11, swift 4

like image 4
NickDK Avatar answered Nov 06 '22 11:11

NickDK