Search code examples
swiftuiimagetvosapple-tv

Creating a UIImage from a remote LSR file


I'm trying to create a UIImage with one of Apple's new layered image files that's hosted on a remote server.

The sample code below downloads the lsr file correctly (the data var holds a value), but creating a new NSImage with it results in a nil value. Ignore the fact that this code is synchronous and inefficient.

if let url = NSURL(string: "http://path/to/my/layered/image.lsr") {
    if let data = NSData(contentsOfURL: url) {
        let image = UIImage(data: data) // `image` var is nil here
        imageView?.image = image
    }
}

Any thoughts on how to download an LSR and create a UIImage with it?


Solution

  • That's how i solved it:

    1. Convert you .lsr file to a .lcr file doing this from console: xcrun --sdk appletvos layerutil --c your_file.lsr
    2. Upload your_file.lcr on your server
    3. Put these two functions into an util class:

      func getDataFromUrl(url:NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError? ) -> Void)) {
          NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
              completion(data: data, response: response, error: error)
          }.resume()
      }
      
      func downloadImage(url: NSURL, imageView: UIImageView){
          print("Started downloading \"\(url.URLByDeletingPathExtension!.lastPathComponent!)\".")
          getDataFromUrl(url) { (data, response, error)  in
              dispatch_async(dispatch_get_main_queue()) { () -> Void in
                  guard let data = data where error == nil else { return }
                  print("Finished downloading \"\(url.URLByDeletingPathExtension!.lastPathComponent!)\".")
                  imageView.image = UIImage(data: data)
              }
          }
      }
      
    4. Use it like this:

      if let checkedUrl = NSURL(string: "http://domain/path/to/your_file.lcr") {
          self.my_ui_view.contentMode = .ScaleAspectFit
          downloadImage(checkedUrl, imageView: self.my_ui_view.contentMode)
      }
      

    This will use the image without saving it into the document directory, if you need that solution, ask me and i'll share.