Learn Courses My Dashboard

SwiftUI and Camera

Hi all . I am new to swift or app development . Please help me if i am understanding the following properly .

  1. swiftUI is new so there is no native component to use camera , we need to use UIKit or AVFoudation framework classes to use camera .
  2. I used UIViewControllerRepresentable to take pic and its working .
  3. i wish to save this image and other data to coreData . i can save the rest of the data to CoreData but struggling with image. my Entity has an attribute of pic of type Binary data . i am trying to convert the Image to png data
    let imageData = image.pngData()
    its not allowing me to use .pngData() as it is available for UIImage only and i am using Image for my image type.

if i change the
@State private var image: Image? to UIImage?
I cannot use the following code in SwiftUI
image?
.resizable()
.frame(width: 150, height: 150)
.padding()

How should i address this .

Regards

-Bobby

Hey @bobby-cwc! Welcome to the code crew forums!

Great job making a camera app in SwiftUI!

I would advise against directly saving the image in CoreData. Images are BLOBs (Binary Large Objects), and its size can vary to less than a Megabyte (MB) to a few tens or hundreds of Megabytes (MB).

What I would suggest is to write the image to disk using FileManager, and store the file’s URL in CoreData instead of the actual file itself.

Basically, you’ll use FileManager to access the documents folder of your app, and use it to store your blobs. In CoreData, you’ll save the URL as a reference to the files/images you save on disk. This way, you won’t face attribute size limit issues since you won’t be storing any blobs directly in your SQLite database.

You’ll still need to encode your image as Data when you write it to disk, so the mechanism of encoding and decoding from Data into UIImage and vice versa should be the same.

If you need the code on how to do this, I found a solution which is very similar in StackOverflow:


If you need to show your UIImage as an Image in SwiftUI, you can use:

let aUIImage = UIImage(named: "image.png")

Image(uiImage: aUIImage)
    .resizable()
    .frame(width: 150, height: 150)
    .padding()