How to store Image, MP3 data in DocumentDirectory And use it from Document Directory?

1. Store Image in DocumentDirectory and use from DocumentDirectory.

–> Store Image:

NSData *webData1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:IMG_URL]];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"test.png"]];

[webData1 writeToFile:localFilePath atomically:YES];

 

–> Display Image from it in anyelse in project:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"test.png"];

UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];

ImageView.image = img;

 

2. Store MP3 in DocumentDirectory and use from DocumentDirectory.

–> Store MP3:

NSData *webData1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:MP3_URL]];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"test.mp3"]];

[webData1 writeToFile:localFilePath atomically:YES];

 

–> Play MP3 from it in anyelse in project:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *getMp3Path = [documentsDirectory stringByAppendingPathComponent:@"test.mp3"];

NSData *_objectData = [NSData dataWithContentsOfFile:getMp3Path];

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

[audioSession setActive:YES error:nil];

player = [[AVAudioPlayer alloc]  initWithData:_objectData error:&error];

player.delegate = self;

[player prepareToPlay];