Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to save and fetch image data from documents directory in iOS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.08k
    Comment on it


    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:-

     

     

     

     

     

    You can also download the sample project from the link given below:-

     

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: