Wednesday 30 April 2014

Creating file in NSTemporary​Directory

NSString *fileName = @"sample.txt";
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
NSString *contentsOfFile = @"Sample text.";
NSData *data =  [contentsOfFile dataUsingEncoding:NSUTF8StringEncoding];
[data writeToFile:path atomically:YES];

Tuesday 29 April 2014

Change the Selection Color of Cell

UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor cyanColor];
cell.selectedBackgroundView = bgColorView;
cell.textLabel.highlightedTextColor = [UIColor grayColor];

Fetch Contacts (Address Book)

-(void)getAllContacts
{

    CFErrorRef *error = nil;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);

    __block BOOL accessGranted = NO;
    if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS 6
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            accessGranted = granted;
            dispatch_semaphore_signal(sema);
        });
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);

    }
    else { // we're on iOS 5 or older
        accessGranted = YES;
    }

    if (accessGranted) {


        NSLog(@"Fetching contact info ----> ");

        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
        ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
        CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName);
        CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);

        for (int i = 0; i < nPeople; i++)
        {

            ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);

            //get First Name and Last Name

            NSString *firstName =(__bridge NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);

            NSString *lastName = (__bridge NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);

            NSLog(@"First name = %@ Last name = %@",firstName,lastName);

           //get Phone Numbers;

            ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
            for(CFIndex i=0;i<ABMultiValueGetCount(multiPhones);i++) {

                CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
                NSString *phoneNumber = (__bridge NSString *) phoneNumberRef;

                NSLog(@"Phone number = %@",phoneNumber);
            }

            // get contacts picture, if pic doesn't exists, show standart one

            NSData  *imgData = (__bridge NSData *)ABPersonCopyImageData(person);

            NSLog(@"Image data= %@",imgData);


            //get Contact email

            ABMultiValueRef multiEmails = ABRecordCopyValue(person, kABPersonEmailProperty);

            for (CFIndex i=0; i<ABMultiValueGetCount(multiEmails); i++) {
                CFStringRef contactEmailRef = ABMultiValueCopyValueAtIndex(multiEmails, i);
                NSString *contactEmail = (__bridge NSString *)contactEmailRef;

                 NSLog(@"emails =%@", contactEmail);

            }

        }


    } else {

        NSLog(@"Cannot fetch Contacts :( ");


    }

}

Thursday 24 April 2014

Save and Load UIImage in Documents Directory

- (void)saveImage: (UIImage*)image
{
if (image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithString: @"test.png"] ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
}
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: @"test.png"] ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}

Tuesday 8 April 2014

NSFile​Manager - Common Tasks

Creating a Directory
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *imagesPath = [documentsPath stringByAppendingPathComponent:@"images"];
if (![fileManager fileExistsAtPath:imagesPath]) {
    [fileManager createDirectoryAtPath:imagesPath withIntermediateDirectories:NO attributes:nil error:nil];
}  

Determining If A File Exists
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"file.txt"];
BOOL fileExists = [fileManager fileExistsAtPath:filePath];

Listing All Files In A Directory
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
NSArray *contents = [fileManager contentsOfDirectoryAtURL:bundleURL
                               includingPropertiesForKeys:@[]
                                                  options:NSDirectoryEnumerationSkipsHiddenFiles
                                                    error:nil];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pathExtension == 'png'"];
for (NSURL *fileURL in [contents filteredArrayUsingPredicate:predicate]) {
    // Enumerate each .png file in directory
}
Reference 1