قالب وردپرس درنا توس
Home / IOS Development / An assistant to work with temporary files in Swift – Ole Begemann

An assistant to work with temporary files in Swift – Ole Begemann



I often find that I need to create a temporary file in code for some operation and every time it gets a little bother: I have to find a suitable temp directory, make sure I give the file a unique name and must not forget to delete the file when I finish it.

In fact, "Create" is the wrong word because usually the API I use will take care of create the file – I & # 39; I should only provide a URL that points to the desired location on the disk. For example, think that your app provides the ability to share a report as a PDF file. You will probably create a UIGraphicsPDFRenderer to render the PDF file and then call the writePDF method and submit a URL to a temporary file that you plan to deliver to the iOS share sheet.

I recently wrote a small Swift helper to make this task easier. You can use it as follows. TemporaryFile TemporaryFile TemporaryFile tmp = = try TemporaryFile ( creatingTempDirectoryForFilename : "report.pdf" )

This creates a new, unique temporary catalog. Note that the directory is empty ̵

1; as I mentioned, TemporaryFile does not create the file for you. Instead, it provides a directory where you can safely create as many files as you want without worrying about naming conflicts.

  • TemporaryFile has two characteristics. directoryURL is the URL of the temp directory it was created. fileURL is the URL of a file in that directory, with the name you specified in the initialiser:

      print   (  tmp .   directoryURL .  . ] 
      // → / var / folders / v8 / tft1q ... / T / ... -8DC6DD131DC1 
      print   (  tmp .   fileURL [19659020].   path ) 
      // → /var/folders/v8/tft1q.../T/...-8DC6DD131DC1/report.pdf
    

    And again note that the file is not still exists – it's your job to make it, usually by sending URL to another API that produces the outputs:

      la    renderer    =    UIGraphicsPDFRenderer   ( ... 
     ] 
      sample    reproducer    writePDF   (  to .:.    tmp    fileURL ) [19659050] {   Context    i 
          // Drawing Code 
          / / ... 
    } 
    

    You are free to create m ore files with other names in the directory, but the type TemporaryFile is currently only created to save a single file address. It would be a nice improvement to give it a number of additional file addresses.

  • After creating the file, the value TemporaryFile is designed to be transferred to your app to the object to use the file (for example, who called the feature that created the file). Once the object is complete and the file is no longer required, it may call deleteDirectory the method to delete the temporary directory, including all files in it:

      // Eg. pass temp file to UIActivityController to share 
      // ... 
      // When done, call deleteDirectory 
      try    tmp .   deleteDirectory   () [19659015] I was counting on automating this step - you could create  TemporaryFile  a class and call  deleteDirectory  in its deinitializer. I decided because the behavior can be surprising for a user of the type. If you add the ability to configure the deletion behavior via an initialization flag, there will be another nice improvement. 

  • Here is the full code (Swift 4.0):

      import    Foundation 
    
      /// A cover around a temporary file in a temporary directory. The catalog 
      /// is specially created for the file, so it's safe to delete when you are 
      /// done to work with the file. 
      /// 
      /// Call `deleteDirectory` when you no longer need the file. [19659000] struct    TemporaryFile [19659000] {
          la    directoryURL :    URL 
          la    fileURL  :    URL 
          /// Deletes the temporary directory and all the files in it. [19659000]] [19659000] deleteDirectory :    ()    casts    ->    Feid 
    
          /// Creates a temporary directory with a unique name and initializes the recipient 
          /// with a `fileURL` which represents a file named` filename` in the 
          /// directory. 
          /// 
          /// - Note: This file does not create!  ]   [ ]   [TTDC]     [19659000] [ ]   [19659000]     deleteDirectory )    =    sample    File .   standard 
                .   urlForUniqueTemporaryDirectory   () 
              itself .   directoryURL    =    catalog 
              even .   fileURL    =    directory .   appendingPathComponent   ([19659019] filename ) 
              even . [19659000]]    {19659053] =    deleteDirectory 
        } 
    } 
    
      extension    File    {
          / // Creates a temporary directory with a unique name and returns the URL. 
          /// 
          /// - Returns: A tuple of the directory URL and a deletion feature. 
          /// Call the function to delete the directory after you finish it. 
          /// 
          /// - Note: You should not trust the existence of the temporary directory 
          /// after the app has finished. 
          FUNC    urlForUniqueTemporaryDirectory   (?   PreferredName :    String      =    nil )    cast 
              -> [[19659011] [ ] :    URL     deleteDirectory :    ()    kaster    ->    void ) 
         ] {
              la    basename    =    preferredName    ??    UUID   () .    uuidString 
    
              var    counter    =    0 
              var    createdSubdirectory :    URL      =    nil 
              repeat    
             [19659957] 
                      la [19659006] subdirName    =    counter    ==    0       basename  : [19659013] "   (  basename ) [19659220] -.    (19659019] counts )   «
                      la    directory    =    temporaryDirectory 
                         [19659046]  appendingPathComponent   (  subdirName  [19659006] : 
    

    :

    ] ]
    sample createDirectory [ by : directory with IntermediateDirectories : [19659158] false )
    createdSubdirectory = directory
    } catch CocoaError [19659020]. fileWriteFileExists {
    // The capture file is incorrect and try again with a different name.
    // Other errors propagate to the caller.
    counter + = ] 1
    }
    } mens createdSubdirectory == nil

    la catalog = createdSubdirectory !
    la deleteDirectory . void = {
    sample even removeItem ([1,965,901 1] to [19659000] 19659012]: Catalog )
    }
    Return ( Catalog DeleteDirectory )
    }
    }


    Source link