Thursday, June 14, 2012

Save UIImage from url

You can save image from url  to documents folder
/* save image from url */
- (void) saveImageFromURL:(NSString *) folder file:(NSString *)fileName url:(NSString*)fileURL {   
    NSString *filePath;
    [self removeFileFromDocuments:folder file:fileName];
    NSString* documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    if([folder length] == 0) {
        filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
    } else {
        filePath = [[[[documentsDirectory stringByAppendingString:@"/"] stringByAppendingString:folder] stringByAppendingString:@"/"] stringByAppendingString:fileName]; 
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
   
    if(![fileManager fileExistsAtPath:filePath]) {       
        // Get an image from the URL below
        UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]]];
        NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)];
        [data writeToFile:filePath atomically:YES];
        [image release];
    }
   
}
You can be too get & save by NSURLRequest
- (UIImage*) getSynchronousImage:(NSString*)fileURL {
    NSError * err;
    NSURLResponse * response;
   
    NSString *strURL = [fileURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:strURL]];

    NSData * receivedData = [NSURLConnection sendSynchronousRequest:imageRequest
                                                  returningResponse:&response
                                                              error:&err];
    if( !receivedData ){
        /* Handle error */
        NSLog(@"Error:%@",[err description]);
    }
    /* Check response */
    UIImage *image = [[UIImage alloc] initWithData:receivedData];
                      
    return image;

}



No comments:

Post a Comment