UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Handling Files Opened from Mail Attachments

Forums > SwiftUI

@GP-16  

I'm creating an app that allows users to open HTML attachments from Mail, copies the file into the app Documents folder, then displays the files using WKWebView. The app will also allow users to open files from the Documents folder.

I'm having touble running the filemanger code when the app is launched from Mail. I see documentation for didFinishLaunchingWithOptions in UIKit, but I was hoping to use the SwiftUI Lifecycle for this project.

Can anyone point me in the right direction to run code based on launching from a Mail attachment?

Thanks!

2      

@GP-16  

I think I've solved this myself...please feel free to comment if you see any issues:

import SwiftUI

@main

struct MyApp: App {

    var body: some Scene {

        WindowGroup {

            ContentView()

                //When the View is launched by an incoming file from another app (Mail, etc), 
                //import the file into Documents and delete the contents of Documents/Inbox

                .onOpenURL(perform: { url in
                    let FM = FileManager.default
                    let documentsdirurl = FM.urls(for: .documentDirectory, in: .userDomainMask).first!
                    let inboxdirURL = documentsdirurl.appendingPathComponent("Inbox")

                    //Call a function that moves a file to a desitination directory and increments 
                    //the name if there is an existing one with the same name
                    //the function returns the new URL

                    let fileURL = moveFile(fromURL: url, toDirURL: documentsdirurl)

                    print(fileURL.path)

                    //Cleanup the Inbox

                    do {
                        let files = try FM.contentsOfDirectory(at: inboxdirURL, 
                                                  includingPropertiesForKeys: nil, 
                                                  options: .skipsHiddenFiles)
                        for file in files {
                            try FileManager.default.removeItem(at: file)
                        }
                    }

                    catch {
                            print(error)
                    }

                })
        }

    }
}

//This function takes a file URL and and desination directory URL and moves the 
//file to the new directory it and adds a number to the end 
//of the file if there is an existing file with the same name

func moveFile(fromURL:URL, toDirURL:URL) -> URL {

    let FM = FileManager.default
    let fromFilename = fromURL.lastPathComponent
    let fromFileExt = fromURL.pathExtension
    var toURL = toDirURL.appendingPathComponent(fromFilename)
    let toFileExt = fromFileExt
    var toFilenameRoot : String!
    var toFilename : String!
    var counter = 0

    //Trim the extension from the filename

    if fromFilename.hasSuffix(fromFileExt) {
        toFilenameRoot = String(fromFilename.prefix(fromFilename.count - (fromFileExt.count+1)))
    }

    //If there is an existing file in the destination with the same name, 
    //try adding a number to then end until there is a unique name (File-1.ext, File-2.ext, etc.)

    while FM.fileExists(atPath: toURL.path) {
        counter += 1
        toFilename =  "\(toFilenameRoot!)-\(counter).\(toFileExt)"
        toURL = toDirURL.appendingPathComponent(toFilename)

    }

    //Once there is a unique filename, move the file from the source to the 
    //destination directory with the new name

    do {
        try FM.moveItem(at: fromURL, to: toURL)
            //print("file moved from:", fromURL.path, "to:", toURL.path)
    }
    catch {
            print(error)
    }

   //return the URL of the file at the new location

    return toURL
}

2      

Please show me for a beginner how you organized the file transfer from the attachment. How can I make the user click on the attached file in the email to get into the app, where my deep link should be? I'm a lot of googling, but couldn't find how to run your code. Please, help me!

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.