Problem with getting images from server - iphone

I'm trying to fetch images from url. Can someone point where i get wrong here is my code?
NSString *filesContent = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.projects-demo.com/iphone/xml/Menu.xml"] ];
DDXMLDocument *ddDoc = [[DDXMLDocument alloc] initWithXMLString:filesContent options:0 error:nil];
DDXMLElement *ddMenu = [ddDoc rootElement];
NSArray *ddChildren = [ddMenu children];
for (int j = 0 ;j < [ddChildren count]; j++) {
DDXMLElement *image1st = [[ddMenu elementsForName:[NSString stringWithFormat:#"cookingType%d",j+1]] objectAtIndex:0];
for (DDXMLNode *n in [image1st children]) {
// if ([[n name] isEqualToString: #"cookingType"]) {
MenuModel *model = [[MenuModel alloc] init];
NSLog(#"image of cooking........%#",[n stringValue]);
model.imgsrc = [n stringValue];
[listofimages addObject:model];
//ss
//======
NSData *mydata = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:model.imgsrc]];
NSLog(#"printing my data ....",mydata);
UIImage *myimage = [[UIImage alloc] initWithData:mydata];
I tried to print nsDAta but it get nothing.

Just an observation, your NSLog for the variable myData, misses %#, not sure if this is just a copy and paste error or something that the HTML doesn't show.
Also try and Log [myData length] there might be a problem with the download.
Last, I would recommend that you do all your URL calls asynchronously.
It would look somewhat like this
`
-(void) loadingThumnailFormURL:(NSString *) thumbnailURL {
[imageData release];
imageData = [[NSMutableData alloc] init];
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:thumbnailURL]];
NSURLConnection *urlConnection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
[urlRequest release];
[urlConnection start];
}`
Needless to say you have to implement the delegate methods for NSURLConnection and capture the data.

Related

Load Web-Content Asynchronously

I am trying to load web content asynchronously. I have a large amount of web calls in my viewdidappear method and my app is very unresponsive. I understand the concepts of synchronous and asynchronous loading of content, but don't know how to tell if this is being done asynchronously. The code below is simply embedded in my viewdidappear method, and I assume it is loading synchronously. How would I edit this to make it load asynchronously? Thank you all!
NSString *strURLtwo = [NSString stringWithFormat:#"http://website.com/json.php?
id=%#&lat1=%#&lon1=%#",id, lat, lon];
NSData *dataURLtwo = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURLtwo]];
NSArray *readJsonArray = [NSJSONSerialization JSONObjectWithData:dataURLtwo options:0
error:nil];
NSDictionary *element1 = [readJsonArray objectAtIndex:0];
NSString *name = [element1 objectForKey:#"name"];
NSString *address = [element1 objectForKey:#"address"];
NSString *phone = [element1 objectForKey:#"phone"];
You can use NSURLConnectionDelegate:
// Your public fetch method
-(void)fetchData
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://website.com/json.php?id=%#&lat1=%#&lon1=%#",id, lat, lon]];
// Put that URL into an NSURLRequest
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
// Create a connection that will exchange this request for data from the URL
connection = [[NSURLConnection alloc] initWithRequest:req
delegate:self
startImmediately:YES];
}
Implement the delegate methods:
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
// Add the incoming chunk of data to the container we are keeping
// The data always comes in the correct order
[jsonData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
// All data is downloaded. Do your stuff with the data
NSArray *readJsonArray = [NSJSONSerialization jsonData options:0 error:nil];
NSDictionary *element1 = [readJsonArray objectAtIndex:0];
NSString *name = [element1 objectForKey:#"name"];
NSString *address = [element1 objectForKey:#"address"];
NSString *phone = [element1 objectForKey:#"phone"];
jsonData = nil;
connection = nil;
}
// Show AlertView if error
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
connection = nil;
jsonData = nil;
NSString *errorString = [NSString stringWithFormat:#"Fetch failed: %#", [error localizedDescription]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertView show];
}
For asynchronous web content loading, I recommend you to use AFNetworking . It'll solve lots of your major headache of networking in future. How to do:
1) subclass AFHTTPCLient, for example:
//WebClientHelper.h
#import "AFHTTPClient.h"
#interface WebClientHelper : AFHTTPClient{
}
+(WebClientHelper *)sharedClient;
#end
//WebClientHelper.m
#import "WebClientHelper.h"
#import "AFHTTPRequestOperation.h"
NSString *const gWebBaseURL = #"http://whateverBaseURL.com/";
#implementation WebClientHelper
+(WebClientHelper *)sharedClient
{
static WebClientHelper * _sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:gWebBaseURL]];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFHTTPRequestOperation class]];
return self;
}
#end
2) Request asynchronously your web content, put this code in any relevant part
NSString *testNewsURL = #"http://whatever.com";
NSURL *url = [NSURL URLWithString:testNewsURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operationHttp =
[[WebClientHelper sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *szResponse = [[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"Response: %#", szResponse );
//PUT your code here
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Operation Error: %#", error.localizedDescription);
}];
[[WebClientHelper sharedClient] enqueueHTTPRequestOperation:operationHttp];

Prevent iCloud Backup

I make and app that the people download content and they can access it offline, it likes a catalogue. But Apple reject it because it baking up in iCloud i I'm doing the following but it seems not working.
Funciones.m
+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL {
const char* filePath = [[URL path] fileSystemRepresentation];
const char* attrName = "com.apple.MobileBackup";
u_int8_t attrValue = 1;
int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
return result == 0;
}
Update.m
- (void)updateImg:(NSString *)tipo {
//tomamos el ultimo update
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSTimeInterval time = [defaults doubleForKey:#"lastUpdate"];
NSLog(#"%f", time);
CatalogoAppDelegate *app = [[UIApplication sharedApplication] delegate];
NSString *post = [NSString stringWithFormat:#"lastUpdate=%f", time];
NSData *postData = [post dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:NO];
NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc] init] autorelease];
NSString *url = [NSString stringWithFormat:#"%#iPhone/update%#Img.php", app.serverUrl, tipo];
[urlRequest setURL:[NSURL URLWithString:url]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:postData];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if(urlData) {
NSString *aStr = [[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]autorelease];
//NSLog(#"%#: %#", tipo, aStr);
NSArray *temp = [aStr componentsSeparatedByString:#";"];
//Direccionl Local de la APP
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
for (int i=0; i<[temp count]; i++) {
NSString *tempImg = [NSString stringWithFormat:#"%#", [temp objectAtIndex:i]];
//NSLog(#"%#", tempImg);
//pedimos cada url
NSURL *tempURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#images/%#/%#", app.serverUrl, tipo, tempImg]];
//[Funciones addSkipBackupAttributeToItemAtURL:tempURL];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:tempURL]];
NSLog(#"%#images/%#/%#", app.serverUrl, tipo, tempImg);
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#", docDir, tempImg];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data1 writeToFile:pngFilePath atomically:YES];
NSURL *backUrl = [NSURL fileURLWithPath:pngFilePath];
[Funciones addSkipBackupAttributeToItemAtURL:backUrl];
}
}
[self performSelectorInBackground:#selector(finUpdate) withObject:nil];
}
Any idea what I am doing wrong?
Thanks
setxattr provides a result indicating success or an error, and Apple's addSkipBackupAttributeToItemAtURL: method checks for an error and passes this information back to your code. Your code simply ignores it. Start by determining if it's returning an error or not.
Maybe it's because your app is compatible with iOS 5.0.
Do not backup variable is only available since 5.1. Details here http://developer.apple.com/library/ios/#qa/qa1719/_index.html#//apple_ref/doc/uid/DTS40011342

Iphone sdk, memory leak

im new with objective-c. I have problem with memory leaking when developing iphone app. Leaking utility in Xcode shows that leaking problem with 'combArr'->'results' object. There is my function which parsing json from url and returns NSArray:
- (NSArray *)getListing2:(NSString *)item
from:(int)country {
//sending post request with some params
NSString *post = [#"product=" stringByAppendingString:item];
NSString *countryStr = [NSString stringWithFormat:#"&country=%d", country];
post = [post stringByAppendingString:countryStr];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *url = [prefs objectForKey:#"urlToApi"];
url = [url stringByAppendingString:#"/get-items/"];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
[request release];
//receiving json
NSString *jsonString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
SBJsonParser *json = [[SBJsonParser alloc] init];
NSError *error = nil;
//parsing json to nsdictionary
NSDictionary *results = [[NSDictionary alloc] initWithDictionary:[json objectWithString:jsonString error:&error]];
[json release];
[jsonString release];
//generate array of items
NSMutableArray *listOfItems = [[NSMutableArray alloc] init];
for (int i = 0; i < [[results objectForKey:#"data"] count]; i++) {
[listOfItems addObject:[[results objectForKey:#"data"] objectForKey:[NSString stringWithFormat:#"%d", i]]];
}
//saving items array and count info object into one array
NSArray * returnArr = [[[NSArray arrayWithObjects:listOfItems, [results valueForKey:#"count_info"], nil] retain] autorelease];
[listOfItems release];
[results release];
return returnArr;
}
And i executing this function here:
myApi *itemsApi = [[myApi alloc] init];
NSArray *combArr = [[izdApi getListing2:item from:countryId] retain];
[itemsApi release];
listOfItems = [[combArr objectAtIndex:0] retain];
if([listOfItems count] > 0){
priceArr = [[combArr objectAtIndex:1] retain];
}
else{
totalCount = 0;
}
[combArr release];
Thank you for helping
Every time you allocate memory, you must release it. (alloc, copy, retain).
You are releasing myApi, not itemsApi. Try this...
myApi *itemsApi = [[itemsApi alloc] init];
NSArray *combArr = [[izdApi getListing2:item from:countryId] retain];
[itemsApi release];
listOfItems = [[combArr objectAtIndex:0] retain];
if([listOfItems count] > 0){
priceArr = [[combArr objectAtIndex:1] retain];
}
else{
totalCount = 0;
}
[combArr release];
If you are using Xcode 4, Try turning on ARC. In short, ARC handles the releasing of all memory. A little burden off your shoulders and one less thing for you to worry about.

NSMutableArray returns null?

I have a UITableView that gets populated my a NSMutableArray. This is how I have it set up in my .h
#interface processViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *processList;
}
#property (copy, readwrite) NSMutableArray *processList;
and my .m
#synthesize processList;
-(void)viewDidLoad {
processList = [[NSMutableArray alloc] init];
}
I put a NSLog on it on the viewDidLoad, and it displays just fine. But after I run a action, the processList array returns null. Any ideas why?
ThanksCoulton
EDIT 1:
- (void)startUploads {
// Start UIActivity in the top
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// Start Pool
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Display results for testing purposes (commented out)
NSArray *resultstwo = [database executeQuery:#"SELECT * FROM processes"];
for (NSDictionary *rowtwo in resultstwo) {
// Get ID
int getUserIDcount = 0;
NSArray *getUserIDInfo = [database executeQuery:#"SELECT * FROM login"];
for (NSDictionary *getUserIDRow in getUserIDInfo) {
getUserIDcount++;
NSString *oneUserID = [getUserIDRow valueForKey:#"id"];
theUserID = [NSString stringWithFormat:#"%#", oneUserID];
}
// If theUserID exists...
if (getUserIDcount == 0) {
//myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector: #selector(checkLogin) userInfo: nil repeats: NO];
} else {
// Get URL of image
NSString *sqlImageUploadPathOne = #"./../Documents/";
NSString *sqlImageUploadPathTwo = [rowtwo valueForKey:#"image"];
NSString *getAlbumID = [rowtwo valueForKey:#"album"];
NSString *sqlImageUploadPath = [NSString stringWithFormat:#"%#%#",sqlImageUploadPathOne,sqlImageUploadPathTwo];
//testLabel.text = #"Uploading...";
// Display Image in UIImageView (uploadImageHidden)
UIImage *attemptImage = [UIImage imageNamed:sqlImageUploadPath];
[uploadImageHidden setImage:attemptImage];
// Upload to server
NSData *imageData = UIImageJPEGRepresentation(uploadImageHidden.image, 90);
NSString *urlStringOne = #"http://myflashpics.com/iphone_processes/upload.php?album=";
NSString *urlStringTwo = #"&id=";
NSString *urlString = [NSString stringWithFormat:#"%#%#%#%#",urlStringOne,getAlbumID,urlStringTwo,theUserID];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
//NSLog(#"%#", returnString);
if ([returnString rangeOfString:#"yes"].location == NSNotFound) {
// Fail
} else {
// Delete image if successful
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *myFilePath = [documentsDirectoryPath stringByAppendingPathComponent:sqlImageUploadPathTwo];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:myFilePath error:NULL];
[database executeNonQuery:#"DELETE FROM processes WHERE image=?", sqlImageUploadPathTwo];
// Get Photo ID
NSArray *myWords = [returnString componentsSeparatedByString:#" "];
NSString *photoID = [myWords objectAtIndex:1];
NSString *usernameID = [myWords objectAtIndex:2];
NSString *defaultName = #"Photo uploaded from the flashpics iPhone application";
// Get Thumbnail URL
NSString *thumbnailURLOne = #"http://myflashpics.com/users/";
NSString *thumbnailURLTwo = #"/pictures/thumbnails/";
NSString *thumbnailURLThree = #".jpg";
NSString *thumbnailURL = [NSString stringWithFormat:#"%#%#%#%#%#",thumbnailURLOne,usernameID,thumbnailURLTwo,photoID,thumbnailURLThree];
// Download thumbnail
//NSLog(#"Downloading...");
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:thumbnailURL]]];
//NSLog(#"%f,%f",image.size.width,image.size.height);
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//NSLog(#"%#",docDir);
//NSLog(#"saving jpeg");
NSString *jpegFilePath = [NSString stringWithFormat:#"%#/%#_thumbnail.jpg",docDir,photoID];
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.2f)];//1.0f = 100% quality
[data2 writeToFile:jpegFilePath atomically:YES];
//NSLog(#"saving image done");
[image release];
// Put in database
NSString *thumbnailEnd = #"_thumbnail.jpg";
NSString *thumbnailLocation = [NSString stringWithFormat:#"%#%#",photoID,thumbnailEnd];
int theCount = 0;
NSArray *getUserIDInfotoo = [database executeQuery:#"SELECT * FROM images WHERE id=?",photoID];
for (NSDictionary *getUserIDRowtoo in getUserIDInfotoo) {
theCount++;
}
if (theCount == 0) {
[database executeNonQuery:#"INSERT INTO images (id, name, thumbnail, album) VALUES (?, ?, ?, ?)", photoID, defaultName, thumbnailLocation, getAlbumID];
}
//[NSThread detachNewThreadSelector:#selector(updateImages) toTarget:RootViewController withObject:nil];
//myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector: #selector(updateImages) userInfo: nil repeats: NO];
}
[request release];
[returnString release];
}
//NSLog([rowtwo valueForKey:#"image"]);
//NSLog([rowtwo valueForKey:#"album"]);
}
[pool release];
// Stop the UIActivity in the top bar
TableViewAppDelegate *dataCeter = (TableViewAppDelegate *)[[UIApplication sharedApplication] delegate];
if ([dataCeter.dataTen isEqualToString:#""]) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
}
Edit 2:
Where the startUploads gets called (different .m)
processViewController *processTable = [[processViewController alloc] initWithNibName:#"processView.xib" bundle:nil];
[processTable startUploads];
[processTable release];
More code would be helpful but here are some suggestions:
Check if startUploads is being called before the view is loaded. The view will only be loaded when it is accessed for the first time to be added to a superview.
Consider initializing processList in your init method instead of viewDidLoad both to solve #1 and b/c the view can loaded & unloaded by iOS independently of the lifecycle of the viewController (depending on what other views you are displaying and whether any memory warnings occur).
Make sure you are releasing processList in dealloc. You only need to release it in viewDidUnload if it is recreated and loaded in viewDidLoad.
Your code sample doesn't show when startUploads is being called and you aren't adding any items to processList so it's hard to tell if the above is relevant. Post some more code and I'll revise my answer accordingly.
good luck!
[EDIT: added example code]
The code fragments you posted are not a complete implementation of a view controller and the associated objects that interact with it. Given the code I have seen, your application design does not conform to MVC (Model/View/Controller) design pattern and I would be doing things a bit differently. However, I don't want to make assumptions about code I haven't seen or your ultimate intent or ability as a developer. I can't write your app for you, just trying to directly help you with the specific question you asked regarding why your NSMutableArray property remains null after the startUploads action completed. With that in mind, here are my edits to the code you posted:
processViewController.m - add the following:
- (id)initWithNibNamed:(NSString *)nibName bundle:(NSBundle *)bundle {
self = [super initWithNibNamed:nibName bundle:bundle];
if (self) {
processList = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dealloc {
self.processList = nil;
[super dealloc];
}
different.m
- (void)displayProcessVC {
ProcessViewController *processVC = [[ProcessViewController alloc] initWithNibNamed:#"processView.xib" bundle:nil];
NSLog(#"Different:displayProcessVC BEFORE STARTING UPLOAD, processList = %#", processVC.processList);
[processVC startUploads];
NSLog(#"Different:displayProcessVC AFTER STARTING UPLOAD, processList = %#", processVC.processList);
// would normally present process VC here
[processVC release];
}
Hope this helps.

Problem regarding webservices image cant displayed in the out put

NSURL *url=[NSURL URLWithString:elementurl];
NSLog(#"url %#", url);
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(#"data = %#, length = %i", data, [data length]);
UIImage *image = [[UIImage alloc] initWithData:data];
[data release];
iam not getting the data can any one suggest another method
pragma mark --------------------------
pragma mark Load UserImage
-(void)loadUserImage{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *frameImagePath = [profileInfoDict objectForKey:#"photo"];
imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:frameImagePath]];
if([imageData length] == 0){
/*NSString *imagePath = [[NSString alloc] initWithFormat:#"%#/%#",[[NSBundle mainBundle] resourcePath],#"no_image.png"];
UIImage image = [[UIImage alloc] initWithContentsOfFile:imagePath];
[item setObject:image forKey:#"itemImage"];
[imagePath release];
[image release];/
}
else {
[self performSelectorOnMainThread:#selector(imageget:) withObject:imageData waitUntilDone:NO];
}
[pool release];
}
-(void)imageget:(NSData *)data
{
UIImage *image = [[UIImage alloc] initWithData:data];
userImageImageView.contentMode = UIViewContentModeScaleAspectFit;
userImage=image;
userImageImageView.image = image;
[[mAppDelegate.userInfoArray objectAtIndex:1] setValue:image forKey:#"Image"];
}
The method you have used is good for small images. If you are trying to download big images it will not do it properly.
You can use the below code
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
To establish connection
(void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData
(void)connectionDidFinishLoading:(NSURLConnection*)theConnection
(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
and above method is used to receive data, error handling etc...
Now apply your own logic by using this methods.