قالب وردپرس درنا توس
Home / IOS Development / FileManager – NSHipster

FileManager – NSHipster



One of the most rewarding experiences you can have as a developer
is to teach young people to program.
If you ever grow jaded by how fundamentally destroyed all software is,
There is nothing like looking at a concept as a recursion
click for the first time
to compensate for the world's fatigue.

My favorite way to introduce the concept of programming
is to put all the ingredients for a peanut butter and jelly sandwich
and ask the class give me instructions for assembly
as if I were a robot 🤖.
Punchline is that computer
takes each instruction as literally as possible,
often with unexpected results.
Ask the robot to "put peanut butter on the bread",
and you can end up with an unopened jar of jif
flattering and erm of Wonder Bread.
Do not forget to specify which part of the bread to be applied to the gel?
Do not be surprised if it ends on the outer crust.
And so on.
Children love it.

The lesson to break down a complex process in discrete steps
is a great enclosure of programming.
And the malicious correspondence from lack of specificity
echo analogy of "programming as wish to create"
from our article about numericCast (_ 🙂 .

But let's take the metaphor one step further,
and imagine it instead of ordering a single robot
( sudo )
make a sandwich,
You write instructions for a thousand different robots.
Big and small, fast and slow;
some have 4 arms instead of 2,
others swing in the air,
maybe somebody read everything in reverse.
Think about what would happen if more robots tried to make a sandwich
simultaneous.
Or imagine your instructions
can be read by robots that will not be built for another 40 years,
on which peanut butter is packed in capsules
and jelly comes exclusively like a gas.

It's like what it's like to interact with a file system.

The only chance we have to make something that works
is to exploit the abstraction power.
On Apple platforms,
This functionality is provided by the foundation's framework
using File Manager .

We can not possibly cover all that is to know
about working with file systems in a single article,
so this week,
Let's take a look at the operations you're most likely to perform
When you build an app.


File Manager provides an easy way to create, read, move, copy and delete
both files and directories,
whether on local or network drives or iCloud ubiquitous containers.

The common currency for all these operations is paths and file addresses.

Trails and File Addresses

Objects on the file system can be identified in some different ways.
For example, each of the following represents
location of the same text document:

  • Path: /Users/NSHipster/Documents/article.md
  • File Address: file: ///Users/NSHipster/Documents/article.md [1
    9659013] File Address : file: ///.file/id=1234567.7654321/

Trails are slant-bounded ( / ) strings that represent a place
in the catalog hierarchy.
File addresses are URLs with a file: // the scheme in addition to a file path.
File Reference Addresses identify the location of a file
uses a unique identifier separated from any directory structure.

Of them,
you will mostly relate to the first two,
which identifies files and directories using a relational path.
That path may be certainly
and provide full placement of a resource from the root directory,
or it may be relative
and show how to get to a resource from a given point of departure.
Absolute URLs begin with / ,
while relative URLs begin with
./ (the current directory),
../ (parent directory), or
~ (the current user's home directory).

File Manager has methods that accept both paths and URLs -
often with variations of the same method for both.
In general, the use of URLs is preferred for lanes,
as they are more flexible to work with.
(it's also easier to convert from a web address to a path than vice versa).

Finding Files and Directories

The first step to working with a file or directory
is to find it on the file system.
Standard locations vary on different platforms,
so rather than manually constructing paths like / System or ~ / Documents ,
you use File Manager method url (for: in: appropriate For: create :)
to find the right place for what you want.

The first parameter takes one of the values ​​specified by
FileManager.SearchPathDirectory .
These determine what kind of standard directory you are looking for,
such as "Documents" or "Caches."

The other parameter passes a
FileManager.SearchPathDomainMask value,
which determines the extent of where you are looking for.
For example,
.application Catalog may refer to / Programs in the local domain
. url ( to : documentDirectory
                             in .:. userDomainMask
                             appropriateFor [19659031]: nil
                             skape : false )

  NSFileManagers    *   File    =    [  NSFileManagers    defaultManager ];   NSString    *   documentsPath    = 
      [  NSSearchPathForDirectoriesInDomains   (  NSDocumentDirectory     NSUserDomainMask     YES )    firstObject ]; 
  NSString    *   filepath    =    [  documentsPath    stringByAppendingPathComponent [19659031]:   @ "file.txt" ]; 

A file exists

You can check to see if a file exist in one place before trying to read it,
or will avoid overwriting an existing one.
To do this, call the file Existing (by Path :) method:

  la    fileURL :    URL 
  la    FileExists    =    File    Standard    FileExists   (  atPath .: ..    fileURL    path [19659031]) 

  NSURL    *   fileURL ; 
  NSFileManagers    *   File    =    [  NSFileManagers    defaultManager  ] 
  BOOL    fileExists    =    [  ] fileManager    fileExistsAtPath : [  fileURL    path ]; 

Get information About a file

The file system stores different parts of metadata
about each file and directory in the system.
You can access them using File Manager Method Attributes By Item (by Path :) .
The resulting dictionary contains attributes marked by File Attribute Key values,
including .creation Date : la fileURL : URL
la attributes =
FileManager . standard attributesOfItem ( atPath . fileURL lanes ).
La Prepared [19659024] = Attributes [ Prepared ]

  NSURL    *   fileURL ; 
  NSFileManagers    *   File    =    [  NSFileManagers    defaultManager ]; 

  NSError    *   error    =    nil ;    NSDictionary [19659024] *   attributes    =    [  [  File    attributesOfItemAtPath : [  fileURL    path ] 
                                                           error [19659025]: [19659027] &   Error ]; 
  NSDate    * [19659035] creationDate    =    attributes   [  NSFileCreationDate ]; 

Listing files in a directory

To list the contents of a directory,
ring File Manager method
Content Of Directory (at: including Properties for Keys: Options 🙂 .
If you intend to access some metadata properties,
as described in the previous section
(for example, get the modification date of each file in a directory),
Specify these to ensure that these attributes are cached.
The option for this method allows you to skip
hidden files and / or descendants. la directoryURL : URL
la content =
try FileManager . standard ~~ POS = TRUNC contentOfDirectory ( on :. directoryURL
                                                 includingPropertiesForKeys : null
                                                 alternatives [19659031]: [. shipHiddenFiles ])
for file in content {
// …
]}

  NSFileManagers    *   File    =    [  NSFileManagers    defaultManager ]; 
  NSURL    *   bundleURL    =    [  NSBundle    mainBundle ]    bundleURL ];            =    [  [ ]    ContentsOfDirectoryAtURL :   bundleURL 
 includingPropertiesForKeys : @ [] 
                                                    alternatives [19659079]:   NSDirectoryEnumerationSkipsHiddenFiles 
                                                      Error :   nil ]; 

NSPredicate * predicated = [ NSPredicate predicateWithFormat : @ "pathExtension =="; png & # 39; ]; for [ NSURL * filURL in [ content filteredArrayUsingPredicate : preached ]) [[19659040] { // Summarize each .png file in the directory }

Recursively lists files in a directory

If you want to go through each subdirectory at a particular location recursively,
You can do that by creating a file Manager.Directory Enumerator items
with disc (by Path 🙂 method:

  la    directoryURL :    URL 

  if    la    enumerator    = 
            
          

File standard enumerator ( atPath . directoryURL lane ). [19659026] for case la path as String in enumerator { // Skip entries with & # 39; _ & # 39; for example, whose path . harPrefix ( "_" ) { enumerator . ShipDescendants () } } }

  NSFileManagers    *   File    =    [  NSFileManagers    defaultManager [19659025]]; 
  NSURL    *   bundleURL    =    [  NSBundle    mainBundle [19659031]]    bundleURL ]; 
  NSDirectoryEnumerator    *   enumerators    =    [    File    enumeratorAtURL :   bundleURL   includingPropertiesForKeys : @ [  NSURLNameKey     NSURLIsDirectoryKey ] 
                                                           alternatives :  :   NSDirectoryEnumerationSkipsHiddenFiles 
                                                      Errorhandler : ^   BOOL [19659031] (  NSURL    *   NSURL    *   ]                 ]                 
          NSLog [19659023] (  @ "[Error]% @ (% @)"     error     url  ]); 
          return    no ; 
    } 

      return    Yes ; 
}]; 

  NSMutableArray    *   mutableFileURLs [19659024] =    [  NSMutableArray    series ];   to   (  NSURL    *   fileURL    in    enumerator )    {
      NSString    *   filename  ];   fileURL    getResourceValue :  &   file name    Forkey :   NSURLNameKey    error :   nil :     ]]; 

      NSNumber    *   isDirectory ; 
        fileURL    getResourceValue :  &   isDirectory    Forkey : [19659035] NSURLIsDirectoryKey    error :   nil  ]]; 

      // Skip directories with & # 39; _ & # 39; prefix, for example, 
      if    ([  filename    hasPrefix :   @ "_" ]    &&    [  isDirectory    ] boolValue ])    {
         [  enumerator  shipDescendants ]; 
          continue ; ]       [   [  isDirectory    boolValue ]]    {
         [  mutableFileURLs    addObject  addObject  ]:   fileURL ]; [19659062]} 
} 

Create a Catalog

To create a directory,
call method create Catalog (on: with Intermediate Catalogs: attributes :) .
In the Unix parlor, sets with Intermediate Catalogs parameter for true true true
corresponds to transferring -p the option to mkdir .

  try    FileManager .   standard .   createDirectory   (  at :    directoryURL  
                                         with Intermediate Directories :    true  
                                         attributes :    nil ) [19659137] NSFileManagers    *   File    =    [  NSFileManagers    defaultManager ];   NSString    *   documentsPath    = [19659062] [  NSSearchPathForDirectoriesInDomains   (  NSDocumentDirectory  
                                          NSUserDomainMask  
                                          YES )    firstObject ]; 
  NSString    *   imagesPath    =    [  documentsPath    stringByAppendingPathComponent :   @ "images" ];       [  [  File    fileExistsAtPath :   imagesPath ])    {
      NSError    *   ] error    =    nil  ; 
      [ ]    createDirectoryAtPath :   imagesPath 
             with IntermediateDirectories :   NO 
                              attributes :   nil 
                                   error [19659027] ]: &   error ]; 
} 

Delete a file or directory

To delete a file or directory,
call remove :

  la    fileURL :    URL 
  try    FileManager .  . 19659027]   removeItem   (  at :    fileURL ) 

  NSFileManagers    *   File    =    [  NSFile Managers    defaultManager ];   NSString    *   documentsPath    = 
      [  NSSearchPathForDirectoriesInDomains   (  NSDocumentDirectory  
                                          NSUserDomainMask  
                                          YES )    firstObject ]; 
  NSString    *   filepath    =    [  documentsPath    stringByAppendingPathComponent [19659031]:   @ "image.png" ]; 
  NSError    *   error    =    nil ;         [  [  File    removeIte mAtPath :   filepath    error :  &   error [19659025]]    {
      NSLog   (  @ «[Error]] ]; 
} 

FileManagerDelegate

File Manager Manager may optionally appoint a delegate
to verify that it will perform a particular file operation.
This is a convenient way to review all file operations in your app,
and a good place to factorize and centralize business logic,
for example, which files should be protected from deletion.

There are four operations covered
FileManagerDelegate protocol:
move, copy, remove and associate items –
each with variations to work with paths and URLs,
as well as how to proceed after an error occurs:

If you wondered when you can make your own File Manager
Instead of using this shared instance,
This is it.

From the documentation:

You should associate your delegate
with a unique instance of File Manager class,
instead of the shared occurrence. ] [File] FileManager [ ] File : NSObject FileManagerDelegate {
func : File
                              
shouldRemoveItemAt URL : URL ) -> Boolean
{
// Do not delete PDFs
return URL . pathExtension ! ]

= CustomFileManagerDelegate () / [MainstrextreferencestofileManagerogdeleger
la [19659070] fileManager = FileManager

File . Issue = Issue

  NSFile Managers    *   File    =    [  NSFileManagers    lloc [19659031]]   [19659031]]; 
  File     Issue    =    Issue  ;. 

NSURL * bundleURL = [[19659035] NSBundle mainBundle ] bundleURL ]; NSArray * Content = [ File ContentsOfDirectoryAtURL [19659031]: bundleURL includingPropertiesForKeys : @ [] alternatives [19659079]: NSDirectoryEnumerationSkipsHiddenFiles Error : nil ]; for [ filepath in content ) { [ File removeItemAtPath ]: [19659035] filPath error : null ]; } // CustomFileManagerDelegate.m #pragma mark - NSFileManagerDelegate - ( BOOL ) File : ( NSFileManagers * ) File shouldRemoveItemAtURL [19659027] ] :! NSURL * ) URL { return [[ URL lastPathComponent [19659031] ] [19659768]] isEqualToString : @ "pdf" ]; }


When you write an app that interacts with a file system,
You do not know if it's a hard drive or SSD
or if it is formatted with APFS or HFS + or something else.
You do not even know where the disk is:
It can be internal or in a mounted peripheral,
It may be networked, or maybe float around somewhere in the cloud.

The best strategy to make sure things work
over each of the different permutations
is working through File Manager and its associated basic APIs.


Source link