1

How can I load a image from URL in to the MPMediaItemArtwork?

Now I have album art from image assets, see code below.

if NSClassFromString("MPNowPlayingInfoCenter") != nil {
    let image:UIImage = UIImage(named: "logo_player_background")!
    let albumArt = MPMediaItemArtwork(image: image)

    MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = [MPMediaItemPropertyArtist: blogPosts[0].postTitle, MPMediaItemPropertyTitle: blogPosts[0].postArtist, MPMediaItemPropertyArtwork: albumArt];
}
Tobbe
  • 1,825
  • 3
  • 21
  • 37
Dennisch
  • 73
  • 2
  • 10

1 Answers1

3

Best approach is download image Asynchronously and do this copy following functions in your VC used this SO answer for my reference

func downloadImage(url:NSURL, completion: ((image: UIImage?) -> Void)){
        print("Started downloading \"\(url.URLByDeletingPathExtension!.lastPathComponent!)\".")
        getDataFromUrl(url) { data in
            dispatch_async(dispatch_get_main_queue()) {
                print("Finished downloading \"\(url.URLByDeletingPathExtension!.lastPathComponent!)\".")


                completion(image: UIImage(data: data!))

            }
        }
    }

    func getDataFromUrl(url:NSURL, completion: ((data: NSData?) -> Void)) {
        NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
            completion(data: data)
            }.resume()
    }

Then call like this

if NSClassFromString("MPNowPlayingInfoCenter") != nil {
            let image:UIImage = UIImage(named: "logo_player_background")!
            let url = NSURL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") // your url path
            //check your url or anyother condidtions you want 
            downloadImage(url!, completion: { (image) -> Void in
                let albumArt = MPMediaItemArtwork(image: image!)

                MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = [MPMediaItemPropertyArtist: blogPosts[0].postTitle, MPMediaItemPropertyTitle: blogPosts[0].postArtist, MPMediaItemPropertyArtwork: albumArt];
            })

For Synchronous approach Not recommended

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
var test =  UIImage(data: NSData(contentsOfURL: NSURL(string:"http://devhumor.com/wp-content/uploads/2012/04/devhumor.com_pointers.png")))
})
Community
  • 1
  • 1
Imran
  • 2,985
  • 19
  • 33