Hi Reader’s,
This blog includes the concept of how to store and fetch data from document directory. You can easily understand the concept with the help of code given below:-
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
- (IBAction)btnShowImage:(id)sender;
@property (weak, nonatomic) IBOutlet UIImageView *imgView;
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
{
NSData *data;
NSString *filePath;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self saveImageInDocumentsDirectory];
[self fetchImageInDocumentsDirectory:filePath];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSData *)saveImageInDocumentsDirectory
{
NSURL *url= [[NSURL alloc]initWithString:@"https://www.uky.edu/ukat/sites/www.uky.edu.ukat/files/help/mobile/android/apple-logo.png"];
data = [NSData dataWithContentsOfURL:url];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
filePath = [documentsPath stringByAppendingPathComponent:@"image.png"]; //Add the file name
[data writeToFile:filePath atomically:YES];
return data;
}
-(void)fetchImageInDocumentsDirectory:(NSString*)filepath
{
data = [NSData dataWithContentsOfFile:filePath]; // fetch image data from filepath
}
- (IBAction)btnShowImage:(id)sender {
[self showImageFromDocumentDirectory:data];
}
-(void)showImageFromDocumentDirectory:(NSData*)dataOfImage
{
UIImage *convertImageFromNSData = [UIImage imageWithData:dataOfImage];
_imgView.image=convertImageFromNSData;
}
@end
Output:-
![](https://lh3.googleusercontent.com/-x198C_UrsqA/V3I_KjQWcCI/AAAAAAAAF6s/OVRCTrl-fGEWCO4k0G2C-HO6WYDznxd_QCL0B/w351-h624-no/Simulator%2BScreen%2BShot%2BJun%2B28%252C%2B2016%252C%2B2.34.20%2BPM.png)
![](https://lh3.googleusercontent.com/-C_ztaafi0Zg/V3I_MWLFV1I/AAAAAAAAF6s/j9VDAwB4BZUg6HcGZH-0LN-XWSxrH5-gACL0B/w351-h624-no/Simulator%2BScreen%2BShot%2BJun%2B28%252C%2B2016%252C%2B2.35.40%2BPM.png)
You can also download the sample project from the link given below:-
0 Comment(s)