Coder Social home page Coder Social logo

fabiocaccamo / fcfilemanager Goto Github PK

View Code? Open in Web Editor NEW
901.0 28.0 140.0 123 KB

:iphone: :open_file_folder: iOS file manager on top of NSFileManager for simplifying files management.

License: MIT License

Ruby 1.51% Objective-C 98.49%
ios objective-c file manager nsfilemanager pod copy create move delete rename read write files directory xattr exif directories remove list

fcfilemanager's Introduction

FCFileManager Pod version Pod platforms Pod license

iOS File Manager on top of NSFileManager for simplifying files management. It provides many static methods for executing most common operations with few lines of code. It works by default in the Documents directory to allow use of relative paths, but it's possible to work easily on any other directory.

Requirements

  • iOS >= 5.0
  • ARC enabled

Installation

CocoaPods:

pod 'FCFileManager'

Manual install:

Copy FCFileManager.h and FCFileManager.m to your project.

Features

  • Build paths relative to absolute directories (FCFileManager works by default in the Documents directory, so you must build absolute paths only if you need to work outside of the Documents directory)
  • Copy files/directories
  • Create files/directories
  • Check if files/directory exists
  • Get files/directories attributes (creation date, size, ...)
  • List files/directories
  • Move files/directories
  • Read/Write files content in different formats (arrays, custom models, data, dictionaries, images, json, strings, ... )
  • Read/Write xattr (Extended File Attributes)
  • Read images metadata, EXIF data, TIFF data
  • Remove files/directories
  • Rename files/directories
  • Directories are created on the fly
  • Error handling as using NSFileManager

See FCFileManager.h for all of the methods.

Usage examples

Build path:

//my file path, this will be automatically used as it's relative to the Documents directory
NSString *testPath = @"test.txt";
//my file path relative to the temporary directory path
NSString *testPathTemp = [FCFileManager pathForTemporaryDirectoryWithPath:testPath];

/*
All shortcuts suppported:

pathForApplicationSupportDirectory;
pathForCachesDirectory;
pathForDocumentsDirectory;
pathForLibraryDirectory;
pathForMainBundleDirectory;
pathForPlistNamed:(NSString *)name; //look for {{ name }}.plist in the main bundle directory
pathForTemporaryDirectory;
*/

Copy file:

//copy file from Documents directory (public) to ApplicationSupport directory (private)
NSString *testPath = [FCFileManager pathForApplicationSupportDirectoryWithPath:@"test-copy.txt"];
[FCFileManager copyItemAtPath:@"test.txt" toPath:testPath];

Create file:

//create file and write content to it (if it doesn't exist)
[FCFileManager createFileAtPath:@"test.txt" withContent:@"File management has never been so easy!!!"];

Create directories:

//create directories tree for the given path (in this case in the Documents directory)
[FCFileManager createDirectoriesForPath:@"/a/b/c/d/"];

Check if file exists:

//check if file exist and returns YES or NO
BOOL testFileExists = [FCFileManager existsItemAtPath:@"test.txt"];

Move file:

//move file from a path to another and returns YES or NO
[FCFileManager moveItemAtPath:@"test.txt" toPath:@"tests/test.txt"];

Read file:

//read file from path and returns its content (NSString in this case)
NSString *test = [FCFileManager readFileAtPath:@"test.txt"];

Read/Write xattr (Extended File Attributes):

//returns the string-value stored for the specified key, if the key doesn't exist returns nil
NSString *value = [FCFileManager xattrOfItemAtPath:@"test.txt" getValueForKey:"uploaded"];

//set the specified string-value and returns a BOOL result of the operation
BOOL success = [FCFileManager xattrOfItemAtPath:@"test.txt" setValue:@"1" forKey:@"uploaded"];

Read image EXIF data:

//read image file from path and returns its EXIF data
NSDictionary *exifData = [FCFileManager exifDataOfImageAtPath:@"test.jpg"];

Remove file:

//remove file at the specified path
[FCFileManager removeItemAtPath:@"test.txt"];

Rename file:

//rename file at the specified path with the new name
[FCFileManager renameItemAtPath:@"test.txt" withName:@"test-renamed.txt"];

Write file:

NSArray *testContent = [NSArray arrayWithObjects:@"t", @"e", @"s", @"t", nil];

//write file at the specified path with content
[FCFileManager writeFileAtPath:@"test.txt" content:testContent];

Get file/directory size:

//get the file size in bytes
NSNumber *fileSize = [FCFileManager sizeOfFileAtPath:@"test.txt"];

//get the directory size in bytes (including all subdirectories and files inside it)
NSNumber *directorySize = [FCFileManager sizeOfDirectoryAtPath:@"/a/"];

Get file/directory size formatted:

//returns a human-readable file size formatted with the necessary suffix: bytes, KB, MB, GB, TB
NSString *fileSizeFormatted = [FCFileManager sizeFormattedOfFileAtPath:@"test.txt"];

Support development

Donate

License

Released under MIT License.

fcfilemanager's People

Contributors

alecgorge avatar arturmichna avatar czwen avatar ekkog avatar fabiocaccamo avatar shukob avatar supery avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fcfilemanager's Issues

Overwrite support

I understand that this is a minor API change but have the ability to specify overwrite flag when creating files would be helpful.

Thanks! :)

support url

hi

copy appshare file or UIDocumentPickerViewController file as url not support

i hope FCFileManager support this feature

thanks

wish you healthy and happy in work

Fund with Polar

wrong case for writeFileAtPath:content:error:

we never reach this cases

        else if([content isKindOfClass:[NSMutableArray class]])
        {
            [((NSMutableArray *)content) writeToFile:filePath atomically:YES];
        }
        else if([content isKindOfClass:[NSMutableData class]])
        {
            [((NSMutableData *)content) writeToFile:filePath atomically:YES];
        }
        else if([content isKindOfClass:[NSMutableDictionary class]])
        {
            [((NSMutableDictionary *)content) writeToFile:filePath atomically:YES];
        }
        else if([content isKindOfClass:[NSMutableString class]])
        {
            [[((NSString *)content) dataUsingEncoding:NSUTF8StringEncoding] writeToFile:filePath atomically:YES];
        }

because every MutableWhatever is inherited from Whatever

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/doc/uid/20000052-BBCBFBDJ

- (BOOL)isKindOfClass:(Class)aClass

Returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class.

You can use

- (BOOL)isMemberOfClass:(Class)aClass

Returns a Boolean value that indicates whether the receiver is an instance of a given class.

Or remove unneeded cases

Json could also be a NSArray

+(NSDictionary *)readFileAtPathAsJSON:(NSString *)path;

This is assuming JSON file is a dictionary, but it can also be a array

Enhancement : Read and Write Extended File Attributes

Not a pull request, but a mod to allow reading and writing of extended File attributes, cribbed from here: https://github.com/pm-dev/PMUtils/blob/master/Pod/Classes/Foundation%2BPMUtils/NSFileManager%2BPMUtils.m#L62-87

And Mattt Thompson, NSHipster here: http://nshipster.com/extended-file-attributes/

#import <sys/xattr.h>
#import <sys/stat.h>


+ (NSString *)xattrStringValueForKey:(NSString *)key atPath:(NSString *)path {
   NSURL *anURL = [FCFileManager urlForItemAtPath:(NSString *)path];
    NSString *value = [self xattrStringValueForKey:(NSString *)key atURL:(NSURL *)anURL];
    return value;
}

+ (BOOL)setXAttrStringValue:(NSString *)value forKey:(NSString *)key atPath:(NSString *)path {
    NSURL *anURL = [FCFileManager urlForItemAtPath:(NSString *)path];
    BOOL setIt = [self setXAttrStringValue:(NSString *)value forKey:(NSString *)key atURL:(NSURL         *)anURL];
    return setIt;
}


+ (NSString *)xattrStringValueForKey:(NSString *)key atURL:(NSURL *)URL
{
    NSString *value = nil;
    const char *keyName = key.UTF8String;
    const char *filePath = URL.fileSystemRepresentation;

    ssize_t bufferSize = getxattr(filePath, keyName, NULL, 0, 0, 0);

    if (bufferSize != -1) {
        char *buffer = malloc(bufferSize+1);

        if (buffer) {
            getxattr(filePath, keyName, buffer, bufferSize, 0, 0);
            buffer[bufferSize] = '\0';
            value = [NSString stringWithUTF8String:buffer];
            free(buffer);
        }
    }
    return value;
}

+ (BOOL)setXAttrStringValue:(NSString *)value forKey:(NSString *)key atURL:(NSURL *)URL
{
    int failed = setxattr(URL.fileSystemRepresentation, key.UTF8String, value.UTF8String, value.length, 0, 0);
    return (failed == 0);
}

1.0.12 couldn't compile with Swift

I've updated to 1.0.12 with cocoapods and it said missing "#import <sys/xattr.h>".
The project is in swift. The latest version that works is 1.0.10

Return wrong data of type JSON

+(NSJSONSerialization )readFileAtPathAsJSON:(NSString *)path error:(NSError *)error
{
NSData *data = [self readFileAtPathAsData:path error:error];

if([self isNotError:error])
{
    NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:error];

    if([NSJSONSerialization isValidJSONObject:json])
    {
        return json;
    }
}

return nil;

}

It should be id/NSArray/NSDictionary...

Wrong nil check for (NSError **) error

in .m file line 187:

return (error == nil); should be return ((*error) == nil);

+(BOOL)createFileAtPath:(NSString )path withContent:(NSObject *)content error:(NSError *)error
{
if(![self existsItemAtPath:path] && [self createDirectoriesForFileAtPath:path error:error])
{
[[NSFileManager defaultManager] createFileAtPath:[self absolutePath:path] contents:nil attributes:nil];

    if(content != nil)
    {
        [self writeFileAtPath:path content:content error:error];
    }

    return ((*error) == nil);
}

return NO;

}

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Path directories

When asking for paths from fcfilemanager it does not put the final / at the end of path. Lets say i want a file from mainBunbdle. Then in order to get its path I will have to do this

FCFileManager.pathForMainBundleDirectory()+"/"+fileName

So I have to enter that "/". I was wondering that should be the default behaviour for the defaul paths.

Transform video file from library to NSData object, using full path to that video (in Swift)

How read video file from video library on the phone if we know full path to video file, for example:
/private/var/mobile/Media/DCIM/100APPLE/IMG_0011.MOV

I tried to use that path in NSData like this:
let videoData = try NSData(contentsOfFile: "/private/var/mobile/Media/DCIM/100APPLE/IMG_0011.MOV", options: NSDataReadingOptions.DataReadingMappedIfSafe)

but I receive this error:

Error Domain=NSCocoaErrorDomain Code=257

"The file “IMG_0011.MOV” couldn’t be opened because you don’t have permission to view it."

UserInfo={NSFilePath=/private/var/mobile/Media/DCIM/100APPLE/IMG_0011.MOV, NSUnderlyingError=0x17d88fc0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

Reading (loading) video file from folder (path) in the aplication works fine, but reading from path that is not in the application folder (like path above) does not work.

So, my question is: how read (get) video file from phone's video library (using full video path) and transform to NSData object, but without saving any data to the disc (using RAM only) during that process?

objectAtIndexedSubscript: requires iOS6.0

The minimum target needs to be raised from 5.0 to 6.0, otherwise there is always a compiler warning about objectAtIndexedSubscript: being only available in 6.0 or later.

tokens[multiplyFactor] in FileManager.m, sizeFormatted:

Fund with Polar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.