如何将网址中的图片加载到MPMediaItemArtwork
?
现在我有来自图片资源的专辑封面,请参阅下面的代码。
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];
}
答案 0 :(得分:1)
最佳方法是异步下载图像并执行此复制以下VC中的函数使用此SO answer 供我参考
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()
}
然后像这样打电话
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];
})
对于同步方法 不推荐
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")))
})