Home > Software design >  SwiftUI - How to translate NSImage for macOS to UIImage for iOS
SwiftUI - How to translate NSImage for macOS to UIImage for iOS

Time:01-11

I am following this tutorial to learn about drag and drop with SwiftUI. https://swiftui-lab.com/drag-drop-with-swiftui/

This is my first time working with getting an image from a URL and the code in the tutorial uses NSImages for macOS, however, I need to build for iOS, therefore, NSImage must be changed to UIImage.

I was able to translate the NSImage to UIImage in the DragableImage struct, however, I am having trouble with the GridCell struct image. Specifically with unwrapping the URL into the img variable and returning it as an overlay on top of the Rectangle. See below code.

struct GridCell: View {
            let active: Bool
            let url: URL?
            
            var body: some View {
            // translate NSImage to UIImage here
                let img = Image(nsImage: url != nil ? NSImage(byReferencing: url!) : NSImage()) 
                    .resizable()
                    .frame(width: 150, height: 150)
                
                return Rectangle()
                    .fill(self.active ? Color.green : Color.clear)
                    .frame(width: 150, height: 150)
                    .overlay(img)
            }
        }

Any help to translate NSImage to UIImage is much appreciated.

CodePudding user response:

If you're using iOS 15 - use AsyncImage instead to load from URL.

let img = AsyncImage(url: url)

Documentation here: https://developer.apple.com/documentation/swiftui/asyncimage


If you need to support iOS 14 or lower, one way to create a UIImage from URL is by defining an extension:

extension UIImage {
  static func fromUrl(url: URL?) -> UIImage {
    if let url = url,
      let data = try? Data(contentsOf: url),
      let image = UIImage(data: data) {
      return image
    } else {
      return UIImage()
    }
  }
}

Then use it as:

let img = Image(uiImage: UIImage.fromUrl(url: url))

Note: if using UIImage and loading remote images, you probably want to load the image asynchronously, not on main thread and maybe in .onAppear - but that is beyond the scope of this question.

  •  Tags:  
  • Related