skip to Main Content

I want after downloading a file that it is automatically put in "My iphone" with a folder created beforehand ( for example "CreateFolder")
Currently I have done this following code but it displays the choice to the user if they want to save it or whatever. What i don’t want
My code :

let urlString = body;

    let url = URL(string: urlString);

    // Récupération du nom du fichier complet + que l'extension + que le nom

    let fileName = String((url!.lastPathComponent)) as String;

    let fileExt  = String((url!.pathExtension)) as String

    let fileNameWithoutExt : String = String(fileName.prefix(fileName.count - (fileExt.count+1)));



    // Create destination URL

    // Création du chemin (système) par défaut ( file:///var/mobile/Containers/Data/Application/6CD1C41B-8D24-466B-A32B-2EC26FE1E8C6/Documents/)

    let documentsUrl:URL =  (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL?)!;

    var destinationFileUrl = documentsUrl.appendingPathComponent("(fileName)");

    

    // Vérification présence fichier si il existe on rajoute un (1) etc..

    var counter = 0;

    var newFileName : String!;

    

    while FileManager().fileExists(atPath: destinationFileUrl.path) {

        counter += 1;

        newFileName =  "(fileNameWithoutExt)_(counter).(fileExt)";

        destinationFileUrl = documentsUrl.appendingPathComponent(newFileName);

       }

    //Create URL to the source file you want to download

    // Création pour le lancement du téléchargement

    let fileURL = URL(string: urlString);

    let sessionConfig = URLSessionConfiguration.default;

    let session = URLSession(configuration: sessionConfig);

    let request = URLRequest(url:fileURL!);

    // Ici commence le téléchargement

    let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in

        if let tempLocalUrl = tempLocalUrl, error == nil {

            // Success

            if let statusCode = (response as? HTTPURLResponse)?.statusCode {

                print("Successfully downloaded. Status code: (statusCode)")

            }

            do {

                // Cette partie permet de copier le fichier stocké ( système Apple ) à l'endroit voulu

                // avec le nouveau du fichier si déjà présent

                try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl);

                do {

                    //Show UIActivityViewController to save the downloaded file

                    // Partie qui permet d'afficher le "popup" pour savoir ce que l'on souhaite faire avec le document téléchargé ( envoyer, enregistrer etc...)

                    // Récupération de tous les fichiers dans le chemin système

                    let contents  = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles);

                    // La boucle permet de parcourir tous les fichiers stocké dans le chemin système d'Apple

                    // Arriver au dernier ( donc celui téléchargé )

                   for indexx in 0..<contents.count {

                       if contents[indexx].lastPathComponent == destinationFileUrl.lastPathComponent {

                        // Ceci met en fil d'attente les éléments et affiche le popup quand la boucle est terminée

                        DispatchQueue.main.async {

                            // Affiche le popup de ce que l'on souhaite faire

                            let activityViewController = UIActivityViewController(activityItems: [contents[indexx]], applicationActivities: nil);

                            self.present(activityViewController, animated: true, completion: nil);

                        }

                       }

                   }

                }

                catch (let err) {

                    print("error: (err)");

                }

            } catch (let writeError) {

                print("Error creating a file (destinationFileUrl) : (writeError)");

            }

        } else {

            print("Error took place while downloading a file. Error description: (error?.localizedDescription ?? "")");

        }

    }

    task.resume();

This is what I would like :
enter image description here

Is it possible to create a folder and put the downloaded file without selecting the destination by the user?
Thanking you in advance

2

Answers


  1. Chosen as BEST ANSWER

    I found a solution for those who are looking to have their file To do this in your Info.plist file add the following 2 keys

    • Application Supports Itunes file sharing
    • Supports opening documents in place

    With my code, you can comment out DispatchQueue.main.async (because useless now) and you will see your files in "In My Iphone"

    enter image description here Thank you very much to @matt


  2. With your document open, click File > Save As.
    Under Save As, select where you want to create your new folder.
    In the Save As dialog box that opens, click New Folder.
    Type the name of your new folder, and press Enter.
    Click Save.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search