Search code examples
objective-cdirectoryextractnsurl

Extract all folders from NSUrl


I have following NSURL, and would need to split it into its various components:

  • The FTP-Url,
  • Each of the folders in order to be able to iterate through them.

What is the best way to do this? I know i can use componentsSeparatedByCharactersInSet: but i would like to be sure that it is the BEST way to do it and that there isnt already a function provided to do just that. (like for example to extract the filename from the NSURL)

 NSURL *url;
 url = [NSURL URLWithString:urlText];  //urlText is ftp.somesite.com/folder1/folder2/folder3

Solution

  • There is a built in way to access it, using the pathComponents property:

    NSURL *url = [NSURL URLWithString:@"ftp://ftp.somesite.com/folder1/folder2/folder3"];
    NSArray *pathComponents = url.pathComponents;
    NSLog(@"%@", pathComponents); // ( @"folder1", @"folder2", @"folder3" )
    

    This is definitely the best approach, since it will handle URL escaping and all that for you.