Max Wells
Max Wells

Reputation: 89

Importing image by opening Files on iPhone using SwiftUI

What I'm trying to do is importing an image by opening File on iPhone, and making that image to be appeared on ContentView by Image(uiImage: self.img) by saving the image to the img variable.

With this youtube video, the current code can open Files and select an image, and can get the fileName of the image, but I'm keep failing at saving it to img variable. It seems the problem is that all I can get is just URL of the image file, not the data of the image.

How can I achieve this?

Here is the current code

import SwiftUI

import UniformTypeIdentifiers

    struct ContentView: View {
        @State var fileName = ""
        @State var openFile = false
        @State var img = UIImage()
        
        var body: some View {
            VStack(spacing: 25){
      
                //file name of the image
                Text(fileName).fontWeight(.bold)
                
                
                //showing the image opend
                Image(uiImage: self.img)
                
                
                Button(action:{
                    openFile.toggle()
                }){
                    Text("Open")
                }
                
            
            }.fileImporter(isPresented: $openFile, allowedContentTypes: [.image]) { (res) in
                
                do{
                    let fileUrl = try res.get()
                    print(fileUrl)
                    
                    self.fileName = fileUrl.lastPathComponent
                    
                } catch{
                    print("Error happend")
                }
               
                
            }
        }
    }
    
    struct Doc : FileDocument {
        
        var url: String
        static var readableContentTypes: [UTType]{[.audio]}
        
        init(url : String) {
            self.url = url
        }
        
        init(configuration : FileDocumentReadConfiguration) throws {
            url = ""
        }
        
        func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
           
            let file = try! FileWrapper(url: URL(fileURLWithPath: url), options: .immediate)
            
            return file
            
        }
    }

Upvotes: 0

Views: 585

Answers (1)

Asperi
Asperi

Reputation: 257493

I assume you wanted this

do{
    let fileUrl = try res.get()
    print(fileUrl)
    
    self.fileName = fileUrl.lastPathComponent

    fileUrl.startAccessingSecurityScopedResource()
    if let imageData = try? Data(contentsOf: fileUrl), 
                       let image = UIImage(data: imageData) {
        self.img = image
    }
    fileUrl.stopAccessingSecurityScopedResource()
    
} catch{
    print("Error happend")
}

Upvotes: 2

Related Questions