Unable to load LCR image in tvOS apps

2019-05-26 02:44发布

问题:

I am trying to load LCR image in UIImageView using "contentsOfFile" method as described in apple document but I am getting error with nil image. Can anyone please confirm how we can load LCR images from server?

Code I am using:

UIImage(contentsOfFile: "LCR file url")

Error I am getting in console:

BOMStorage BOMStorageOpenWithSys(const char , Boolean, BomSys ): can't open: '/LCR file url' No such file or directory

One thing I noticed is it adds "/" in front of my actual url. I think its because its looking for files in local storage. Does anyone know whats the solution of it?

I even tried to use this:

Downloaded file—Load images using imageWithContentsOfFile:

but no use :(

回答1:

Ok I kind of found the work around myself for this problem. So I am posting here if in case anyone else is facing same problem. Below is code with explanation:

if let url = NSURL(string: "https://.lcr-file-url") {
        if let data = NSData(contentsOfURL: url){
          let documents = NSURL(string: NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0])
          let writePath = documents!.URLByAppendingPathComponent("file.lcr")
          data.writeToFile(writePath.absoluteString, atomically: true)
          let image = UIImage(contentsOfFile: writePath.absoluteString)
        }
      }

Basically we need to download the image data and save it in some local file and use contentsOfFile method to have actual image.

If anyone else know better solution than this, I would be happy to hear :)



回答2:

contentsOfFile assumes you're passing along a path to a local file, not a URL of an image hosted on some remote server.

What you should be doing here is loading data into a NSData object and then passing it to UIImage via UIImage(withData: dataFromServer).

To do it synchronously:

if let url = NSURL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") {
    if let data = NSData(contentsOfURL: url){
        let yourImage = UIImage(data: data)
    }
}

The code for which I found in this related question

And here's a blog post on how to do it asynchronously.