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:
- trimmedString= www.abcd.com/images/pqr.jpg
- isSuccessful
- image =null
Thanks in advance.