Ui view freez for long time - ios

I am working on afnetworking, i have web service that takes too much time to load data and i want that UI do not freeze, i used this tutorial to run webservice on background so that i can work on other views as well, but not sucess till yet.
-(void) getArticles :(NSString*)stateAbbre completionHandler:(void (^)(id array))success
{
[MyCommonFunctions showGlobalProgressHUDWithTitle:#"Loading"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *link = [NSString stringWithFormat:#"http://cloud.ilmasoft.com/depilex/depilexs/get_articles_ios.php"];
NSLog(#"%#",link);
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager GET:link parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSDictionary *returnedDealDict = responseObject ;
NSArray *returnArray = [returnedDealDict objectForKey:#"Result"];
for(NSDictionary *dealDict in returnArray)
{
ArticlesDC *articles = [[ArticlesDC alloc] init];
articles.articlesID = [[dealDict objectForKey:#"id"]intValue ];
articles.articleTitle = [dealDict objectForKey:#"title" ];
articles.articleDetail = [dealDict objectForKey:#"details" ];
articles.articleDate = [dealDict objectForKey:#"date" ];
articles.articlePic = [dealDict objectForKey:#"pic" ];
articles.articleThumbPath = [dealDict objectForKey:#"thumb_path" ];
articles.articleStatus = [dealDict objectForKey:#"status" ];
[dataArray addObject:articles];
[MyCommonFunctions dismissGlobalHUD];
}
success(dataArray);
// [MBProgressHUD hideHUDForView:self.view animated:YES];
if (dataArray.count == 0)
{
ALERT_VIEW(#"Please check your internet connection.");
// [MBProgressHUD hideHUDForView:self.view animated:YES];
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
ALERT_VIEW(#"Error occured while loading data.");
// [MBProgressHUD hideHUDForView:self.view animated:YES];
}];
}
and in my view did load method
[self getArticles:nil completionHandler:^(id array) {
articlesArray = array;
[tblView reloadData];
for (ArticlesDC *article in articlesArray)
{
NSString *stringWithoutSpace = [[NSString stringWithFormat:#"http://cloud.ilmasoft.com/depilex/admin/%#", article.articleThumbPath] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString: stringWithoutSpace]];
UIImage *imgOne = [UIImage imageWithData:imageData];
NSString *stringforImg = [[NSString stringWithFormat:#"http://cloud.ilmasoft.com/depilex/admin/%#", article.articlePic] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *imageDta = [NSData dataWithContentsOfURL:[NSURL URLWithString: stringforImg]];
UIImage *imgTwo = [UIImage imageWithData:imageDta];
[dbHandler insertArticlesIntoSqlite:article.articleTitle andDetail:article.articleDetail anddate:article.articleDate andImage:[MyCommonFunctions saveImageInDocuments:imgTwo] andThumb:[MyCommonFunctions saveImageInDocuments:imgOne]];
[defaults setInteger:1 forKey:#"getArticlesOffline"];
[defaults synchronize];
}
}];

The problem is not AF, it's that at the end of that process you call dataWithContentsOfURL twice and this runs directly on the main thread to download some images. You need to move that download to a background thread.

Related

Upload 5 images to server using AFNetworking [duplicate]

This question already has answers here:
AFNetworking multiple files upload
(3 answers)
Closed 6 years ago.
I used Afnetworking in my app,I need to post 5 images to server, 5 images as array, this array was one of my **request parameters.
this is correct way or wrong one, there is any one more performance than it ? -
(IBAction)sPActionButton:(id)sender {
NSUserDefaults *def=[NSUserDefaults standardUserDefaults];
NSString * language=[def objectForKey:#"Language"];
NSString * deviceToken=[def objectForKey:#"dT"];
[par setObject:deviceToken forKey:#"dT"];
NSString *check=[def objectForKey:#"Log"];
[par setObject:check forKey:#"aT"];
//---------------------------------------------
NSString * apiKey=APIKEY;
[par setObject:apiKey forKey:#"aK"];
[par setObject:language forKey:#"lG"];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:10];
for (int x=0; x<_chosenImages.count; x++) {
NSData *imageData = UIImageJPEGRepresentation(_chosenImages[x], 0.5);
NSLog(#"%#",imageData);
NSString *str=[Base64 encode:imageData];
[images addObject:str];
}
NSLog(#"%#",images);
[par setObject:images forKey:#"image[array]"];
if ([self validateAllFields]) {
NSLog(#"par = %#",par);
//-----------------------------------------------
[MBProgressHUD showHUDAddedTo:self.view animated:NO];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:[NSString stringWithFormat:#"%#/sellPrp?",BASEURl] parameters:par
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Data"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
[MBProgressHUD hideHUDForView:self.view animated:NO];
}];
}
}
- (void)prepareForImagePosting
{
if (imageCount < self.arrAllPostImages.count)//arrAllPostImages array contains images for posting and imageCount acts as iterator
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init]; //Prepare the dictionary which contains image for posting
[dict setObject:#"1" forKey:#"upload"];
[dict setObject:[[self.arrAllPostImages objectAtIndex:imageCount]objectForKey:#"SelectedPhoto"] forKey:#"post_image"];
[self postImage:dict];
}
else
return;
}
- (void)postImage: (NSMutableDictionary *)dictPostImages
{
NSError *error = nil;
NSString *url = POSTIMAGELINK;
NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setObject:[dictPostImages objectForKey:#"upload"] forKey:#"upload"];
NSData *jsonRequestDict = [NSJSONSerialization dataWithJSONObject:postDict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonCommand = [[NSString alloc] initWithData:jsonRequestDict encoding:NSUTF8StringEncoding];
NSLog(#"***jsonCommand***%#",jsonCommand);
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:jsonCommand,#"requestParam", nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
if (isEnteredInFailureBlock == NO)
{
//here Image is posted
NSData *postPicData=UIImageJPEGRepresentation([dictPostImages objectForKey:#"post_image"], 0.5) ;
[formData appendPartWithFileData:postPicData
name:#"post_image"
fileName:[NSString stringWithFormat:#"image%d.jpg",imageCount]
mimeType:#"image/*"];
}
else
{
}
} success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSError *error = nil;
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
NSMutableDictionary *jsonResponseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSLog(#"Response Dictionary:: %#",jsonResponseDict);
if ([[jsonResponseDict objectForKey:#"status"] intValue] == 1)
{
if (isEnteredInFailureBlock == NO)
{
[self.arrSuccessfullyPostedImagesDetails addObject:jsonResponseDict];
if (appDel.successfullImgPostingCount == appDel.totalPostingImagesCount)
{
}
else
{
appDel.successfullImgPostingCount++;
imageCount++;
[self prepareForImagePosting];
}
}
else
{
self.arrSuccessfullyPostedImagesDetails = [[NSMutableArray alloc]init];
appDel.successfullImgPostingCount = 0;
appDel.totalPostingImagesCount = 0;
imageCount = 0;
return;
}
}
else
{
self.arrSuccessfullyPostedImagesDetails = [[NSMutableArray alloc]init];
appDel.successfullImgPostingCount = 0;
appDel.totalPostingImagesCount = 0;
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Request Error: %#", error);
isEnteredInFailureBlock = YES;
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Posting Unsuccessful" delegate:nil cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
// if image is not successfully posted then the server is informed with #"upload" #"0" so that the entire post is deleted from server
NSMutableDictionary *failureDict = [[NSMutableDictionary alloc]init];
[failureDict setObject:#"0" forKey:#"upload"];
[self postImage:failureDict];
}];
}

SVProgressHUD dismiss not working in custom class

Firstly, I've added some functions which need to call from different ViewControllers in one class file. For those function, I've add SVProgressHUD as preprocess and dismiss after all process is finished. SVProgressHUD is displaying correctly before process is started. But after process, SVProgressHUD is never dismissed at all. Please let me know how to solve that issue.
I've added [SVProgressHUD dismiss]; in all process is finished. But never dismissed.
common.m
- (NSDictionary *) loadBlahClass:(NSString *)paramUserId {
[SVProgressHUD showWithStatus:#"Loading Cards..."];
__block NSDictionary *jsonResponse;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.responseSerializer.acceptableContentTypes setByAddingObject:#"application/json"];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSString *urlStr = [NSString stringWithFormat:#"MY_URL"];
[manager GET:urlStr parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[SVProgressHUD dismiss];
dispatch_semaphore_signal(semaphore);
}
failure:
^(AFHTTPRequestOperation *operation, NSError *error) {
[SVProgressHUD dismiss];
[self showAlert:APP_NAME alertMessage:[error localizedDescription]];
dispatch_semaphore_signal(semaphore);
}];
[SVProgressHUD dismiss];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return jsonResponse;
}
testViewController.m
_allTableData = [[NSMutableArray alloc]init];
NSDictionary *jsonResponse = [commClass loadBlahClass:strUserId];
NSNumber *status = [jsonResponse valueForKey:#"Success"];
NSString *message = [jsonResponse valueForKey:#"Message"];
NSArray *dataArray = [jsonResponse valueForKey:#"lstCC"];
if([status intValue] == 1) {
for(int i=0; i<[dataArray count]; i++) {
//working .......
}
[_ccTable reloadData];
[SVProgressHUD dismiss];
} else {
[commClass showAlert:APP_NAME alertMessage:message];
[SVProgressHUD dismiss];
}
I've found answer. Something like that.
[SVProgressHUD show];
__block BOOL result;
dispatch_async(queue, ^{
result = [self autanticate];
NSLog(#"autantication result = %d", result);
result = [self getCSRFToken];
NSLog(#"Login success result = %d", result);
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
})
});

How to return an NSArray in the success block, iOS, Objective-C

this is my code. I want to return an array with data after data assign from the web service to the array.I have use block to check.
this is from my header file...
typedef void(^FailureBlock)(NSError *error);
typedef void(^SuccessBlock) (NSMutableArray *responseArray);
this is my implementation file ....
- (void)setupConnectionWithsuccess:(SuccessBlock)success failure:(FailureBlock)failure
{
airportArray = nil;
NSString *airportCode = [NSString stringWithFormat:#"some code"];
NSString *authenticationCode = [NSString stringWithFormat:#"some api"];
NSString *baseurl = [NSString stringWithFormat:#"some url",authenticationCode,airportCode];
// NSString *mainurlString = [NSString stringWithFormat:#""];
// NSURL *mainurl = [NSURL URLWithString:mainurlString];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:baseurl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSArray *mainArray = (NSArray *)responseObject;
airportArray = [[NSMutableArray alloc] init];
for (NSDictionary *all in mainArray) {
airports = [all objectForKey:#"Airport"];
[airportArray addObject:airports];
NSLog(#"%#", airports);
}
if(success){
success(airportArray);
}
//NSLog(#"%#", responseObject);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
UIAlertController *mainAlert = [UIAlertController alertControllerWithTitle:#"Something Wrong!" message:[error localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:mainAlert animated:YES completion:nil];
}];
}
then after success, I want to return the array from this method.how can I do that
- (NSArray *)returnAll
{
[self setupConnectionWithsuccess:^(NSMutableArray *responseArray) {
} failure:^(NSError *error) {
}];
}
please help me with this.I'm new to iOS Block.
Try as follow here i use id because in id you can pass anyobject
- (void)setupConnectionWithsuccess:(void (^)(id responseObject, NSError *error))completion{
airportArray = nil;
NSString *airportCode = [NSString stringWithFormat:#"some code"];
NSString *authenticationCode = [NSString stringWithFormat:#"some api"];
NSString *baseurl = [NSString stringWithFormat:#"some url",authenticationCode,airportCode];
// NSString *mainurlString = [NSString stringWithFormat:#""];
// NSURL *mainurl = [NSURL URLWithString:mainurlString];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:baseurl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSArray *mainArray = (NSArray *)responseObject;
airportArray = [[NSMutableArray alloc] init];
for (NSDictionary *all in mainArray) {
airports = [all objectForKey:#"Airport"];
[airportArray addObject:airports];
NSLog(#"%#", airports);
}
if (completion)
completion(responseObject,nil);
//NSLog(#"%#", responseObject);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (completion)
completion(nil,error);
UIAlertController *mainAlert = [UIAlertController alertControllerWithTitle:#"Something Wrong!" message:[error localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:mainAlert animated:YES completion:nil];
}];}
and to call it
[self setupConnectionWithsuccess:^(id responseObject, NSError *error) {
if (responseObject) {
NSLog(#"responsceObect");
}
}];
It get nothing while your function return. Because your block excute at asynchonize way. you should modify your function to handle the Array data in a block.

Afnetworking late response

I am new to AfNetworking, i want to get array after running my function but i always get crash as it loads data into array very late, is there any way to stop it till it loads all data into array?
-(void) getModelDetails :(NSString*)brandName completionHandler:(void (^)(id array))success
{
NSString *brand = [brandName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *link = [NSString stringWithFormat:#"http://phablet-fix.com/mob/get-model-details.php?model=%#",brand];
NSLog(#"%#",link);
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager GET:link parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSDictionary *returnedDealDict = responseObject ;
NSArray *returnArray = [returnedDealDict objectForKey:#"modeldetails"];
for(NSDictionary *dealDict in returnArray)
{
model = [[ModelDC alloc] init];
model.modelID = [[dealDict objectForKey:#"id"] intValue];
model.model = [dealDict objectForKey:#"model"];
model.mDeviceBrand = [dealDict objectForKey:#"device_brand"];
model.mDeviceType = [dealDict objectForKey:#"device_type"];
model.mProtectionPlanAvilable = [dealDict objectForKey:#"protection_plan_available"];
model.mSilverPlan1year = [dealDict objectForKey:#"silver_plan_price_1year"];
model.mSilverPlan2Year = [dealDict objectForKey:#"silver_plan_price_2year"];
model.mSilverPlan3Year = [dealDict objectForKey:#"silver_plan_price_3year"];
model.mGoldPlan1year = [dealDict objectForKey:#"gold_plan_price_1year"];
model.mGoldPlan2year = [dealDict objectForKey:#"gold_plan_price_2year"];
model.mGoldPlan3Year = [dealDict objectForKey:#"gold_plan_price_3year"];
[dataArray addObject:model];
}
success(dataArray);
[MBProgressHUD hideHUDForView:self.view animated:YES];
if (dataArray.count == 0)
{
ALERT_VIEW(#"Please check your internet connection.");
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
else
{
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
ALERT_VIEW(#"Error occured while loading data.");
[MBProgressHUD hideHUDForView:self.view animated:YES];
}];
}
and in my tableview i get zero data into my array
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath :(NSIndexPath *)indexPath
{
model = [planArray objectAtIndex:indexPath.row];
lblselectYourDevice.text = model.selectedModel;
tblView.hidden = YES;
modelDetailArray = [[NSMutableArray alloc] init];
[self getModelDetails:model.selectedModel completionHandler:^(id array)
{
modelDetailArray = array;
}];
NSLog(#"%d",modelDetailArray.count);
model = [[ModelDC alloc] init];
model = [modelDetailArray objectAtIndex:indexPath.row];
}
This will never work:
modelDetailArray = [[NSMutableArray alloc] init];
[self getModelDetails:model.selectedModel completionHandler:^(id array)
{
modelDetailArray = array;
}];
NSLog(#"%d",modelDetailArray.count);
model = [[ModelDC alloc] init];
model = [modelDetailArray objectAtIndex:indexPath.row];
because you are creating an empty array, asking for it to be populated with data and then immediately using it without waiting for the population to complete (or checking that the data you want was actually obtained).
Change to:
modelDetailArray = nil;
[self getModelDetails:model.selectedModel completionHandler:^(id array) {
modelDetailArray = array;
NSLog(#"%d", modelDetailArray.count);
if (modelDetailArray.count > indexPath.row) {
model = [modelDetailArray objectAtIndex:indexPath.row];
// trigger the UI update or next piece of processing here
} else {
// deal with the error
}
}];
Note that this also isn't creating empty objects that you aren't going to use.

View is not populating data AFNetworking

I am using AFNetworking, my success block works fine, but my view is always loaded first. I am not using table view for my view, there are only labels, and images that need to be refreshed. What should i do now ?
-(void)myVenusWithClubDetail :(NSString *)IDs completionHandler:(void (^)(id array))success
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *link = [NSString stringWithFormat:#"%#",KWSURLVenuDetail];
NSLog(#"%#",IDs);
NSDictionary *params = #{#"Id" : IDs};
NSLog(#"%#",link);
[manager POST:link parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
ClubDetailDC *clubDC = [[ClubDetailDC alloc] init];
clubDC.cDVenuID = [[responseObject objectForKey:#"Id"]integerValue];
clubDC.cDCatID = [[responseObject objectForKey:#"cat_id"]integerValue];
clubDC.cDName = [responseObject objectForKey:#"name"];
clubDC.cDHeadLine = [responseObject objectForKey:#"headline"];
clubDC.cDImage = [responseObject objectForKey:#"image"];
clubDC.cDLong = [responseObject objectForKey:#"long"];
clubDC.cDLat = [responseObject objectForKey:#"lat"];
clubDC.cDAddress = [responseObject objectForKey:#"address"];
clubDC.cDSummary = [responseObject objectForKey:#"summary"];
clubDC.cDStat = [responseObject objectForKey:#"stat"];
clubDC.cDUS = [responseObject objectForKey:#"us"];
clubDC.cDImage = [self loadClubDetailImages:clubDC.cDImage];
[dataArray addObject:clubDC];
success(dataArray);
if (dataArray.count == 0)
{
ALERT_VIEW(#"Please check your internet connection.");
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
ALERT_VIEW(#"Error while loading data.")
}];
}
and my venuVC.m is like this where i want to show data
-(void)reloadView
{
clubDetail = [[ClubDetailDC alloc] init];
venu_dataArray = [[NSMutableArray alloc] init];
upcomingArray = [[NSMutableArray alloc] init];
GET_DBHANDLER
// venu_dataArray = [dbHandler get_club_detail:venuID];
NSString *strVenuID = [NSString stringWithFormat:#"%d",venuID];
NSLog(#"%#",strVenuID);
[dbHandler myVenusWithClubDetail:strVenuID completionHandler:^(id array)
{
venu_dataArray = array;
// NSLog(#"%d",array.count);
}];
}
-(void)viewWillAppear:(BOOL)animated
{
[self reloadView];
for (clubDetail in venu_dataArray)
{
lblDescription.text = [ NSString stringWithFormat:#"Neighborhood:%# Information on whats happening tonight", clubDetail.cDAddress];
[imgClub setImageWithURL:[NSURL URLWithString:clubDetail.cDImage]];
}
UIFont* font_name = [UIFont fontWithName:#"Corbel" size:17];
UIFont* bold_font = [UIFont fontWithName:#"Corbel-Bold" size:17];
lbl_upcomingEvents.font = font_name;
lbl_Unighted.font = bold_font;
lblDescription.font = [UIFont fontWithName:#"Corbel" size:11];
lblCheckIn.font = [UIFont fontWithName:#"Corbel" size:13];
lblCount.font = [UIFont fontWithName:#"Corbel" size:12];
lblGoodEmotion.font = [UIFont fontWithName:#"Corbel" size:14];
lblHotEmotion.font = [UIFont fontWithName:#"Corbel" size:14];
}
My problem is that view is loaded first, then I get the data from success block. Can anyone help?
Thanks.
you can do this in two ways either you write function in in your view, code will be like this
-(void)myVenusWithClubDetail :(NSString *)IDs completionHandler:(void (^)(id array))success
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *link = [NSString stringWithFormat:#"%#",KWSURLVenuDetail];
NSLog(#"%#",IDs);
NSDictionary *params = #{#"Id" : IDs};
NSLog(#"%#",link);
[manager POST:link parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
ClubDetailDC *clubDC = [[ClubDetailDC alloc] init];
clubDC.cDVenuID = [[responseObject objectForKey:#"Id"]integerValue];
clubDC.cDCatID = [[responseObject objectForKey:#"cat_id"]integerValue];
clubDC.cDName = [responseObject objectForKey:#"name"];
clubDC.cDHeadLine = [responseObject objectForKey:#"headline"];
clubDC.cDImage = [responseObject objectForKey:#"image"];
clubDC.cDLong = [responseObject objectForKey:#"long"];
clubDC.cDLat = [responseObject objectForKey:#"lat"];
clubDC.cDAddress = [responseObject objectForKey:#"address"];
clubDC.cDSummary = [responseObject objectForKey:#"summary"];
clubDC.cDStat = [responseObject objectForKey:#"stat"];
clubDC.cDUS = [responseObject objectForKey:#"us"];
clubDC.cDImage = [self loadClubDetailImages:clubDC.cDImage];
for (clubDetail in venu_dataArray)
{
lblDescription.text = [ NSString stringWithFormat:#"Neighborhood:%# Information on whats happening tonight", clubDetail.cDAddress];
[imgClub setImageWithURL:[NSURL URLWithString:clubDetail.cDImage]];
}
[dataArray addObject:clubDC];
success(dataArray);
if (dataArray.count == 0)
{
ALERT_VIEW(#"Please check your internet connection.");
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
ALERT_VIEW(#"Error while loading data.")
}];
}
or if you want to use your function in separete class then do like this in your success block
[dbHandler myVenusWithClubDetail:strVenuID completionHandler:^(id array)
{
venu_dataArray = array;
// NSLog(#"%d",array.count);
for (clubDetail in venu_dataArray)
{
lblDescription.text = [ NSString stringWithFormat:#"Neighborhood:%# Information on whats happening tonight", clubDetail.cDAddress];
[imgClub setImageWithURL:[NSURL URLWithString:clubDetail.cDImage]];
}
}];
Since venue_dataArray is local in reloadView method, you wont be able to iterate it in viewWillAppear.
So I guess, you should move your label assigning code to success block like below:
[dbHandler myVenusWithClubDetail:strVenuID completionHandler:^(id array)
{
venu_dataArray = array;
// NSLog(#"%d",array.count);
for (clubDetail in venu_dataArray)
{
lblDescription.text = [ NSString stringWithFormat:#"Neighborhood:%# Information on whats happening tonight", clubDetail.cDAddress];
[imgClub setImageWithURL:[NSURL URLWithString:clubDetail.cDImage]];
}
}];
Can you post your success function too? If you set the text on your labels and image on your uiimageview everything should be updated accordingly.
Your success function could look something like:
- (void)updateViewsWithData:(NSMutableArray *)dataArray {
var clubDC = dataArray[0];
self.yourLabel.text = clubDC.cDSummary;
self.addressLabel.text = clubDC.cDAddress;
self.imageView.image = clubDC.cDImage;
}
You have to AFNetworking library or something similar to download the image first because I am pretty sure that what you got is the url of the image.
Please comment if you have any more question.
In your code,
clubDC.cDImage = [self loadClubDetailImages:clubDC.cDImage];
This line will fetch the image from server or local directory depending upon how you implemented it. There will be expected delay in getting the image.
self.imageView.image = clubDC.cDImage;
there will be chance that image is not fully downloaded when you are executing above code.

Resources