4

So I want to show an image from a URL.

I know I would first need to make it friendly URL encoded -

.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

for example

if var strUrl = nowplaying.data.first?.track.imageurl {
  strUrl = strUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
 }

However how then do I get it to put it into the MPMediaItemPropertyArtwork.

I have attempted many different things from using a 3rd part kingfisher plugin - but no success.

If someone could show me how to get the following image to show that would be great

http://covers.drn1.com.au/az_B101753_Wish You Were Here_Brain Purist.jpg

RussellHarrower
  • 6,470
  • 21
  • 102
  • 204

1 Answers1

5

You need to setup MPRemoteCommandCenter with its nowPlayingInfo:

    func setupNowPlayingInfo(with artwork: MPMediaItemArtwork) {
        nowPlayingInfo = [
            MPMediaItemPropertyTitle: "Some name",
            MPMediaItemPropertyArtist: "Some name",
            MPMediaItemPropertyArtwork: artwork,
            MPMediaItemPropertyPlaybackDuration: CMTimeGetSeconds(currentItem.duration)
            MPNowPlayingInfoPropertyPlaybackRate: 1,
            MPNowPlayingInfoPropertyElapsedPlaybackTime: CMTimeGetSeconds(currentItem.currentTime())
        ]
    }
   func getData(from url: URL, completion: @escaping (UIImage?) -> Void) {
        URLSession.shared.dataTask(with: url, completionHandler: {(data, response, error) in
            if let data = data {
                completion(UIImage(data:data))
            }
        })
            .resume()
    }

    func getArtBoard() {
        guard let url = URL(string: "http://covers.drn1.com.au/az_B101753_Wish%20You%20Were%20Here_Brain%20Purist.jpg") else { return }
        getData(from: url) { [weak self] image in
            guard let self = self,
                let downloadedImage = image else {
                    return
            }
            let artwork = MPMediaItemArtwork.init(boundsSize: downloadedImage.size, requestHandler: { _ -> UIImage in
                return downloadedImage
            })
            self.setupNowPlayingInfo(with: artwork)
        }
    }

enter image description here

kseniiap
  • 443
  • 1
  • 3
  • 8
  • You can't make a synchronous method wait for an asynchonous method to return its value – Leo Dabus Nov 25 '19 at 16:41
  • 1
    `func getArtBoard(from url: URL, completion: @escaping (MPMediaItemArtwork) -> () ) { URLSession.shared.dataTask(with: url) { data, _, error in guard let data = data, let image = UIImage(data: data) else { if let error = error { print(error) } return } completion(.init(boundsSize: image.size) { _ in image }) }.resume() }` – Leo Dabus Nov 25 '19 at 17:15
  • 2
    then `getArtBoard(from: url) { artboard in // do whatever with your artboard print("finished downloading artboard", artboard.bounds) } ` – Leo Dabus Nov 25 '19 at 17:17