Quote:
Originally Posted by ajitthakali
Is there better way to download Image from a Server to phone.I use NSURL but it crashes sometimes.
Here is the code i used:
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.12312312.com/image.png"]]];
NSString *docDir3 = [NSSearchPathForDirectoriesInDomains(NSDocumentDire ctory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath3 = [NSString stringWithFormat:@"%@/Landing Image.png",docDir3];
NSData *data3 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data3 writeToFile  ngFilePath3 atomically:YES];
|
There are several things wrong with this code.
First and most importantly, It reads data synchronously. That will freeze your UI, which is a bad user experience. The system may even terminate your app if you remain unresponsive for too long. Another poster to this thread posted a link that showed how to do async downloads. (Describing Async downloading is beyond the scope of a single post.)
Secondly, your code reads the data from the server, turns it into a UIImage, then converts the image to NSData, copies that data into ANOTHER NSData object, and then saves that data to a file. Thus you create 3 copies of each image in memory.
You should skip all those intermediate steps and just write the data from the server directly to a file.
Code:
NSData* fileData = [NSData dataWithContentsOfURL:[NSURL
URLWithString:@"http://www.12312312.com/image.png"]];
NSString *docDir3 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath3 = [NSString stringWithFormat:@"%@/Landing Image.png",docDir3];
[fileData writeToFile:pngFilePath3 atomically:YES];[/quote]