Krunal
Krunal

Reputation: 6490

UIImage gets corrupted while Downloading

I have developed iOS App, in which i am downloading image from server and saving it in my Document directory.

But problem which i am facing is, sometimes my images getting corrupted when i download, even if the server response isSuccessful.

Here is my code snippet,

urlFile is path of UIImage which is on server e.g: www.abcd.com/images/pqr.jpg

fileName which i am using for saving image name in my DocDirectory.

- (void)downloadFile:(NSString *)urlFile withName:(NSString *)fileName 
{
    NSString *trimmedString = [urlFile stringByTrimmingCharactersInSet:
                               [NSCharacterSet whitespaceAndNewlineCharacterSet]];

    NSLog(@"trimmedString=%@",trimmedString);
    if ([trimmedString length]>0)
    {
        HTTPEaterResponse *response = [HTTPEater get:[NSString stringWithFormat:@"%@",trimmedString]];

    if ([response isSuccessful])
        {  
           NSLog(@"isSuccessful");
            [self saveImage:[[UIImage alloc] initWithData:[response body]] withName:fileName];
        } else {
            NSLog(@"Url response failed %@", [response description]);
        }
    }

}


    - (void)saveImage:(UIImage *)image withName:(NSString *)name
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        NSData *data = UIImagePNGRepresentation(image);
        NSLog(@"image =%@",image);

        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
        [fileManager createFileAtPath:fullPath contents:data attributes:nil];

    }

When i see my Log, it shows:

Thanks in advance.

Upvotes: 0

Views: 864

Answers (5)

anky_believeMe
anky_believeMe

Reputation: 484

I use the following code and it works for me.

NSData *thumbImageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:ImageURL]];
[thumbImageData writeToFile:cachedThumbnailFileName atomically:YES];
UIImage * image =  [UIImage imageWithContentsOfFile:cachedThumbnailFileName];
imageView.image = image;

Hope it helps you. :)

Upvotes: 2

Abdullah Md. Zubair
Abdullah Md. Zubair

Reputation: 3324

To save image on directory use:

NSString  *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];
[UIImagePNGRepresentation(selectedImage) writeToFile:pngPath atomically:YES];
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];  
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

Upvotes: 1

Shankar BS
Shankar BS

Reputation: 8402

instead u can use, "NSURLRequest" and "NSURLConnection" for example if u get image URL then,

    NSURL* aURL = [NSURL URLWithString:trimmedString];//get the url of string
    NSURLRequest *aReq = [NSURLRequest requestWithURL:aURL];
    NSURLConnection *aConnection = [NSURLConnection connectionWithRequest:aReq delegate:self]; //get a connection to url , since it confirms to delegate u need to implement delegate methods 
    if(aConnection == nil) //if it is nil then cancel and close the request
    { 
       aConnection = nil;  
      [aConnection cancel];
    }


   // after this implement this delegate methods
  - (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)received_data
  {
      if(image_data == nil)    //if data is not initialised initialise it
      {
          image_data = [[NSMutableData alloc]init];
      }

      [self.image_data appendData:received_data];//append the received data

  }
  //this method is called after successful download of the image
  - (void)connectionDidFinishLoading:(NSURLConnection *)connection;
 {
    // UIImage* sampleImage = [UIImage imageWithData:self.image_data];
    // self.image = sampleImage; //convert the data to image 
    //since u hav complete downloaded date in "self.image_data"

    NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/myImage.png"];//set the name of the image and path may it saving in application directory check it out  
    [self.image_data writeToFile:imagePath atomically:YES]; //saving the data with name
 }

Hope this helps u :)

Upvotes: 0

Jignesh B
Jignesh B

Reputation: 508

i suggest yo use SDWebimage Class SDWebimage download.. i think its very helpful to you even i always prefer SDWebimage Library. this are the some things.

An UIImageView category adding web image and cache management to the Cocoa Touch framework
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
Animated GIF support
WebP format support
A background image decompression
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
A guarantee that main thread will never be blocked
Performances!
Use GCD and ARC

Upvotes: 0

wesley
wesley

Reputation: 859

have you logged the response [response body]?

Just try to convert that response as NSData and then save as image. Using Base64Encoding class,you can convert the response as base64Data

NSData *imageData = [NSString base64DataFromString:[response body]];
[self saveImage:[[UIImage alloc] initWithData:imageData] withName:fileName];

Upvotes: 0

Related Questions