UIImage gets corrupted while Downloading - iphone

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.

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

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"];

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];

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

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

Related

MPMoviePlayerController doesn't play newly saved video file

I'm using an imagePickerController to record video. In the imagePickerController:didFinishPickingMediaWithInfo: function I'm trying to set the video to a previously defined MPMoviePlayerController:
if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
NSURL *movieUrl = [info objectForKey:UIImagePickerControllerMediaURL];
[self.moviePlayer setContentURL:movieUrl]];
}
This is working fine and the video is indeed playing.
But I want to save the file for later use. When I do this and use the saved file for the moviePlayer, nothing happens:
I've tried this (saving the data to a new file)
NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *newPath = [directory stringByAppendingPathComponent:#"myMovie.mov"];
NSData *videoData = [NSData dataWithContentsOfURL:movieUrl];
[videoData writeToFile:newPath atomically:NO];
[self.moviePlayer setContentURL:[NSURL URLWithString:newPath]];
or this (copying the temp video file to my document folder)
NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *newPath = [directory stringByAppendingPathComponent:#"myMovie.mov"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
[fileManager copyItemAtPath:[videoUrl path] toPath:newPath error:&error];
[self.moviePlayer setContentURL:[NSURL URLWithString:newPath]];
Without any success, even though the file at newPath does exist... What am I doing wrong?
Ok I finally found the issue. The problem was not in fact with the MPMoviePlayerController but with the line:
[self.moviePlayer setContentURL:[NSURL URLWithString:newPath]];
I fixed it by replacing that line with:
[self.moviePlayer setContentURL:[NSURL fileURLWithPath:newPath isDirectory:NO]];
Hope that will help someone else!
use the code below:
NSData *movieData;
NSError *dataReadingError = nil;
movieData = [NSData dataWithContentsOfURL: movieURL options:NSDataReadingMapped error:&dataReadingError];
if(movieData != nil)
NSLog(#"Successfully loaded the data.");
else
NSLog(#"Failed to load the data with error = %#", dataReadingError);

Check if file exists in resourses/project navigator

I need to check if an image exists in the project navigator. If it doesn't it needs to download it from the internet. The goal is to be able to use images like [UIImage imageNamed:#"23451.jpg"];
So I need to check if the image exists, if not download it. I tried to do this as followed:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//Set image
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:#"12345.jpg"];
//Check if the image exists at a given path
BOOL imageExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];
//If the image doesn't exists download it.
if (!imageExists)
{
NSData* data = UIImageJPEGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"www.mywebsite.com/12345.jpg"]]]);
[data writeToFile:imagePath atomically:YES];
}
If everything goes the right way the image is saved at the above path. But I still am not able to use this image with
[UIImage imageNamed:#"12345.jpg"];
I have got the feeling that i'm saving the images in a different directory than I should be saving them to.
Do you have any idea on how I should do this?
imageNamed will only work form image in the app bundle, not those stored in the Document directory. And you can't add the image to the app bundle, it readonly.
if (!imageExists)
{
NSData* data = UIImageJPEGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"www.mywebsite.com/12345.jpg"]]]);
[data writeToFile:imagePath atomically:YES];
}
There is no need to do this, you are now JPG a JPG:
if (!imageExists)
{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.mywebsite.com/12345.jpg"]];
[data writeToFile:imagePath atomically:YES];
}
NSData* data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:imagePath], 0.8)];
[data writeToFile:imagePath atomically:YES];
I did something similar .. here are some excerpts of the code .. not the complete code ...
- (void)loadAndStoreImage{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL *theurlPortrait = [[NSURL alloc] initWithString:[[DataController sharedDataController].imageResponse objectForKey:#"portraitImageUrl"] ];
NSLog(#"Image url %# ",theurlPortrait);
imageDataPortrait = [NSData dataWithContentsOfURL:theurlPortrait];
[theurlPortrait release];
imagePortrait= [[UIImage alloc]initWithData:imageDataPortrait];
oldPathPortrait = [documentsDirectory stringByAppendingPathComponent:#"pt_wallpaper_1.png"];
NSURL *theurlLandscape = [[NSURL alloc] initWithString:[[DataController sharedDataController].imageResponse objectForKey:#"landscapeImageUrl"]];
imageDataLandscape = [NSData dataWithContentsOfURL:theurlLandscape];
[theurlLandscape release];
imageLandscape= [[UIImage alloc]initWithData:imageDataLandscape];
oldPathLandscape = [documentsDirectory stringByAppendingPathComponent:#"ls_wallpaper_1.png"];
[self replaceImages];
}
-(void)replaceImages{
//check if images were fully downloaded or corrupted.
if (isUserSignedIn) {
if (imageDataPortrait && imageDataLandscape) {
[UIImagePNGRepresentation(imagePortrait) writeToFile:oldPathPortrait atomically:YES];
[UIImagePNGRepresentation(imageLandscape) writeToFile:oldPathLandscape atomically:YES];
NSLog(#"IMAGES REPLACED");
NSDate *currentDate=[NSDate date];
[[ NSUserDefaults standardUserDefaults] setObject:currentDate forKey:#"previousDate"];
}
}
}

How save images in home directory?

I am making an application in which i have use Json parsing. With the help of json parsing i get photo url which is saved in string. To show images in my cell i use this code
NSString *strURL=[NSString stringWithFormat:#"%#", [list_photo objectAtIndex:indexPath.row]];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: strURL]];
CGRect myImage =CGRectMake(13,5,50,50);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:myImage];
[imageView setImage:[UIImage imageWithData: imageData]];
[cell addSubview:imageView];
Now prblem is that when i go back or forword then i have wait for few second to come back on same view. Now i want that i when application is used first tme then i wait for that screen otherwise get images from home directory. How i save these image in my home directory? How access from home directory?
You can save an image in the default documents directory as follows using the imageData;
// Accessing the documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"myImage.png"];
//Writing the image file
[imageData writeToFile:savedImagePath atomically:NO];
You can use this to write a file to your Documents Folder
+(BOOL) downloadFileFromURL:(NSString *) url withLocalName:(NSString*) localName
{
//Get the local file and it's size.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:localName];
NSError *error;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:finalPath error:&error];
NSAssert (error == nil, ([NSString stringWithFormat:#"Error: %#", error]));
if (error) return NO;
int localFileSize = [[fileAttributes objectForKey:NSFileSize] intValue];
//Prepare a request for the desired resource.
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"HEAD"];
//Send the request for just the HTTP header.
NSURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSAssert (error == nil, ([NSString stringWithFormat:#"Error: %#", error]));
if (error) return NO;
//Check the response code
int status = 404;
if ([response respondsToSelector:#selector(statusCode)])
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
status = [httpResponse statusCode];
}
if (status != 200)
{
//file not found
return NO;
}
else
{
//file found
}
//Get the expected file size of the downloaded file
int remoteFileSize = [response expectedContentLength];
//If the file isn't already downloaded, download it.
if (localFileSize != remoteFileSize || (localFileSize == 0))
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];
return YES;
}
//here we may wish to check the dates or the file contents to ensure they are the same file.
//The file is already downloaded
return YES;
}
and this to read:
+(UIImage*) fileAtLocation:(NSString*) docLocation
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:docLocation];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];
NSData *databuffer = [[NSFileManager defaultManager] contentsAtPath:finalPath];
UIImage *image = [UIImage imageWithData:databuffer];
return image;
}

How to load image from documents directory/IPHONE

I am saving the images when there is internet connection in my iphone.
Now i want to load the images which are saved in documents directory. I am getting the path, but the image is not displaying. Please help me in this.
Thanks in advance.
Here is my code:
+(UIImage *) getImagewithName:(NSString*) imagepath
{
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage *gimage=[UIImage imageWithContentsOfFile: [NSString stringWithFormat:#"%#/%#",docDir,imagepath]];
NSLog(#"%#/%#",docDir,imagepath);
return gimage;
}
+(void)DownloadImage:(NSString*)ImagePath {
if ([ImagePath isEqualToString:#""])
return;
UIImage *dimage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http:/uploads/%#",ImagePath]]]];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(#"pathIMAGEPATHS:::::::%#",ImagePath);
NSLog(#"path:::::::%#",docDir);
NSArray *patharr=[ImagePath componentsSeparatedByString:#"."];
NSString* Ext=[NSString stringWithFormat: #"%#",[patharr objectAtIndex:1]];
NSString *FilePath = [NSString stringWithFormat: [NSString stringWithFormat:#"%#/%#",docDir,ImagePath]];
if([Ext isEqualToString:#"png"])
{
NSLog(#"saving png");
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(dimage)];
[data1 writeToFile:FilePath atomically:YES];
}
else if([Ext isEqualToString:#"jpeg"])
{
NSLog(#"saving jpeg");
//NSString *jpegFilePath = [NSString stringWithFormat:#"%#/test.jpeg",docDir];
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(dimage, 1.0f)];//1.0f = 100% quality
[data2 writeToFile:FilePath atomically:YES];
}
else
{
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(dimage)];
[data1 writeToFile:FilePath atomically:YES];
}
NSLog(#"saving image done");
[dimage release];
}
viggio24 makes a good point. But moreover, this code seems incredibly complicated to do something incredibly simple. Why do you download to data, then turn it into an image, just to turn it back into data, and finally write it? And then you read it again and make a new image? Why not just download the file to disk and read it? UIImage will do all the work of managing PNG and JPEG for you. Something like:
+(void)downloadImage:(NSString*)imagePath {
if ([imagePath isEqualToString:#""])
return;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[#"http://110.234.132.132/MBCMcAdmin/uploads" stringByAppendingPathComponent:imagePath]]];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[data writeToFile:[docDir stringByAppendingPathComponent:imagePath] atomically:YES];
}
This is still a horrible idea in most cases, though, since it blocks the calling thread. It's better to do this with NSURLDownload which will do it all for you in the background and tell you when it's done.
I'd simplify the code, and then follow viggio24's comments, making sure that you error check this stuff. You're probably just not reading the file correctly or failing to write it.

iOS: Download image from url and save in device

I am trying to download the image from the url http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg
I am using the following code, but image is not saved in the device. I want to know what I am doing wrong.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg"]];
[NSURLConnection connectionWithRequest:request delegate:self];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:#"pkm.jpg"];
NSData *thedata = NULL;
[thedata writeToFile:localFilePath atomically:YES];
UIImage *img = [[UIImage alloc] initWithData:thedata];
I happen to have exactly what you are looking for.
Get Image From URL
-(UIImage *) getImageFromURL:(NSString *)fileURL {
UIImage * result;
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
result = [UIImage imageWithData:data];
return result;
}
Save Image
-(void) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
if ([[extension lowercaseString] isEqualToString:#"png"]) {
[UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]] options:NSAtomicWrite error:nil];
} else if ([[extension lowercaseString] isEqualToString:#"jpg"] || [[extension lowercaseString] isEqualToString:#"jpeg"]) {
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]] options:NSAtomicWrite error:nil];
} else {
NSLog(#"Image Save Failed\nExtension: (%#) is not recognized, use (PNG/JPG)", extension);
}
}
Load Image
-(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/%#.%#", directoryPath, fileName, extension]];
return result;
}
How-To
//Definitions
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//Get Image From URL
UIImage * imageFromURL = [self getImageFromURL:#"http://www.yourdomain.com/yourImage.png"];
//Save Image to Directory
[self saveImage:imageFromURL withFileName:#"My Image" ofType:#"png" inDirectory:documentsDirectoryPath];
//Load Image From Directory
UIImage * imageFromWeb = [self loadImage:#"My Image" ofType:#"png" inDirectory:documentsDirectoryPath];
If you set theData to nil, what do you expect it to write to the disk?
What you can use is NSData* theData = [NSData dataWithContentsOfURL:yourURLHere]; to load the data from the disk and then save it using writeToFile:atomically:. If you need more control over the loading process or have it in background, look at the documentation of NSURLConnection and the associated guide.
This is the code to download the image from url and save that image in the device and this is the reference link.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg"]];
[NSURLConnection connectionWithRequest:request delegate:self];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:#"pkm.jpg"];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg"]];
[thedata writeToFile:localFilePath atomically:YES];
Get Image From URL
-(UIImage *) getImageFromURL:(NSString *)fileURL {
UIImage * result;
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
result = [UIImage imageWithData:data];
return result;
}
This worked great for me but I ran into memory issues with CFData (store). Fixed it with an autoreleasepool:
-(UIImage *) getImageFromURL:(NSString *)fileURL {
#autoreleasepool {
UIImage * result;
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
result = [UIImage imageWithData:data];
return result;
}
}
Since we are on IOS6 now, you no longer need to write images to disk neccessarily.
Since iOS5 you are now able to set "allow external storage" on an coredata binary attribute.
According to apples release notes it means the following:
Small data values like image thumbnails may be efficiently stored in a
database, but laarge photos or other media are best handled directly by
the file system. You can now specify that the value of a managed
object attribute may be stored as an external record - see setAllowsExternalBinaryDataStorage:
When enabled, Core Data heuristically decides on a per-value basis if
it should save the data directly in the database or store a URI to a
separate file which it manages for you. You cannot query based on the
contents of a binary data property if you use this option.
Hi It is clear that you are writing NULL data to your file.
In your code statement NSData *thedata = NULL; indicates that you assign NULL value to your data.
You are writing NULL data to your file as well.
Please check your code once again.
-(IBAction)BtnDwn:(id)sender
{
[self.actvityIndicator startAnimating];
NSURL *URL = [NSURL URLWithString:self.dataaArray];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error)
{
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath];
NSURL *documentURL = [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:[documentURL path]];
if (exists)
{
NSLog(#"not created");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Download"
message:#"sory,file already exists"
delegate:nil
cancelButtonTitle:#"cancel"
otherButtonTitles:nil];
[alert show];
}
else
{
[[NSFileManager defaultManager] moveItemAtURL:location toURL:documentURL error:nil];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Download"
message:#"Succesfully downloaded"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[self.actvityIndicator stopAnimating];
NSLog(#"wait downloading......");
[alert show];
}
}];
[downloadTask resume];
}
Here is how you can save an image asynchronously in Swift:
requestImage("http://www.asdf.com/89asdf.gif") { (image) -> Void in
let myImage = image
}
func requestImage(url: String, success: (UIImage?) -> Void) {
requestURL(url, success: { (data) -> Void in
if let d = data {
success(UIImage(data: d))
}
})
}
func requestURL(url: String, success: (NSData?) -> Void, error: ((NSError) -> Void)? = nil) {
NSURLConnection.sendAsynchronousRequest(
NSURLRequest(URL: NSURL (string: url)!),
queue: NSOperationQueue.mainQueue(),
completionHandler: { response, data, err in
if let e = err {
error?(e)
} else {
success(data)
}
})
}
Its included as a standard function in my repo:
https://github.com/goktugyil/EZSwiftExtensions
Here's an example of how I download banners to my app. I download the images in the background, and most of my apps do not use reference counting so I release objects.
- (void)viewDidLoad {
[super viewDidLoad];
[NSThread detachNewThreadSelector:#selector(loadImageInBackground) toTarget:self withObject:nil];
}
- (void) loadImageInBackground {
NSURL *url = [[NSURL alloc] initWithString:#"http://yourImagePath.png"];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
[url release];
UIImage *result = [[UIImage alloc] initWithData:data];
[data release];
UIImageView *banner_ImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
[self.view addSubview:banner_ImageView];
banner_ImageView.image = result;
[result release];
}