connectiondidFinishLoading called twice - objective-c

I am new to iphone development. I am able to use the data in connectiondidFinishLoading method.But i see "connection didfinishloading" method called twice.I don't know ,where i am going wrong. Here is my code
Edited code:
again connectionDidFinishLoading called twice
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField==CompanyName)
{
autocompleteTableView.hidden = NO;
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
return YES;
if([CompanyName.text length]==0)
{
autocompleteTableView.hidden = YES;
[popoverController dismissPopoverAnimated:YES];
}
}
return YES;
}
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring
{
data = [[NSMutableData alloc] init];
self.receivedData = data;
[data release];
NSURL *jsonUrl =[NSURL URLWithString:[NSString stringWithFormat:#"http://xxxx=%#",substring]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:jsonUrl];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self ];
//self.connection = connection;a
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
parser = [[NSXMLParser alloc] initWithData:receivedData];
currentHtmlElement=#"5";
[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
[parser release];
if([arr4 count]!=0)
{
self.autocompleteUrls = [[[NSMutableArray alloc] init]autorelease];
UIViewController* popoverContent = [[UIViewController alloc] init]; //ViewController
self.autocompleteUrls = [[NSMutableArray alloc] init];
viewForautoCompleteTableView = [[UIView alloc]initWithFrame:CGRectMake (410, 120,270, 250)];
autocompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0,270,250) style:UITableViewStyleGrouped];
autocompleteTableView.delegate = self;
autocompleteTableView.dataSource = self;
autocompleteTableView.scrollEnabled = YES;
autocompleteTableView.backgroundColor = [UIColor lightTextColor];
autocompleteTableView.rowHeight=28;
autocompleteTableView.backgroundView = nil;
autocompleteTableView.backgroundColor = [UIColor whiteColor];
autocompleteTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
[autocompleteTableView setSeparatorColor:[UIColor orangeColor]];
[viewForautoCompleteTableView setFrame:CGRectMake(210,380 ,autocompleteTableView.frame
.size.width
,autocompleteTableView.frame.size.height)];
[viewForautoCompleteTableView addSubview:autocompleteTableView];
[viewForautoCompleteTableView setBackgroundColor:[UIColor whiteColor]];
CGRect popoverFrame = viewForautoCompleteTableView.frame;
popoverContent.view = viewForautoCompleteTableView;
popoverController = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
popoverController.delegate=self;
[popoverContent release];
[popoverController setPopoverContentSize:CGSizeMake(viewForautoCompleteTableView.frame.size.width, viewForautoCompleteTableView.frame.size.height) animated:NO];
[popoverController presentPopoverFromRect:popoverFrame inView:testscroll permittedArrowDirections:0 animated:YES];
[autocompleteUrls removeAllObjects];
for(int i=0;i<[arr4 count];i++)
{
NSString *curString = [[arr4 objectAtIndex:i] valueForKey:#"Name"];
[autocompleteUrls addObject:curString];
}
}
[autocompleteTableView reloadData];
[connection cancel];
}

you should remove [connection start]; because connection will start automatically after NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:selfstartImmediately:NO];
Edit
a valid NSURLConnection initialization
NSURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#""]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

Related

Objective-C app issue on iOS 11

I wrote an iOS app in Objective-C. Xcode version is 8. It works fine on all devices and iOS versions but when I tried to test this in the iOS device running iOS 11. The “Profile Page” stopped working in the sense that once we navigate to that screen, it becomes touch unresponsive and nothing happens. This page works well with all iOS versions and all device except for those running iOS 11.
Code for Profile page is:
#import "ProfileViewController.h"
#interface ProfileViewController ()
#end
#implementation ProfileViewController
- (void)viewDidLoad
{
[super viewDidLoad];
currentUser = [SingletonClass sharedSingletonClass].settingsDictionary[#"User"];
selectedValues=[NSMutableDictionary dictionary];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
NSMutableDictionary *paramDict=[NSMutableDictionary dictionary];
[paramDict setObject:#"ios" forKey:#"request"];
[paramDict setObject:[NSString stringWithFormat:#"%#",currentUser.user_id] forKey:#"user_id"];
[GeneralWebservices webserviceMainSplashCall:paramDict webserviceName:Webservice_Profile OnCompletion:^(id returnDict, NSError *error) {
if ([returnDict[#"success"] intValue] ==1)
{
[self setProfileData:returnDict[#"data"]];
provinceList=[NSMutableArray arrayWithArray:returnDict[#"provincedata"]];
questions1Array=[NSMutableArray arrayWithArray:returnDict[#"questiondata"]];
}
else
{
[self get_register_data];
[alert show];
}
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}];
}
-(void)setProfileData:(NSMutableDictionary*)dataDict
{
profilePicImageView.imageURL=[NSURL URLWithString:dataDict[#"image_file_thumb"]];
[firstNameLabel setText:dataDict[#"first_name"]];
[lastNameLabel setText:dataDict[#"last_name"]];
[dateOfBirthLabel setText:dataDict[#"user_dob"]];
[postalAddressTextfield setText:dataDict[#"user_address"]];
[mobileTextfield setText:dataDict[#"user_mobile"]];
[question1Textfield setText:dataDict[#"user_answer_1"]];
[question2Textfield setText:dataDict[#"user_answer_2"]];
[LLGButton setTitle:dataDict[#"user_llg"] forState:UIControlStateNormal];
[provinceButton setTitle:dataDict[#"user_province"] forState:UIControlStateNormal];
[districtButton setTitle:dataDict[#"user_district"] forState:UIControlStateNormal];
[villageTextfield setText:dataDict[#"user_village"]];
[question1Button setTitle:dataDict[#"user_question_1"] forState:UIControlStateNormal];
[question2Button setTitle:dataDict[#"user_question_2"] forState:UIControlStateNormal];
[self callforDistrict:#"get_district.php" idForItem:dataDict[#"district_id"]];
[self callforLLG:#"get_llg.php" idForItem:dataDict[#"llg_id"]];
[selectedValues setObject:dataDict[#"user_question_1_id"] forKey:#"user_question_1"];
[selectedValues setObject:dataDict[#"user_question_2_id"] forKey:#"user_question_2"];
[selectedValues setObject:dataDict[#"province_id"] forKey:#"user_province"];
[selectedValues setObject:dataDict[#"district_id"] forKey:#"user_district"];
[selectedValues setObject:dataDict[#"llg_id"] forKey:#"user_llg"];
}
-(void)callforDistrict:(NSString*)serviceName idForItem:(NSString*)idForItem
{
dispatch_async(dispatch_get_main_queue(), ^{
[self getdistdata:idForItem];
});
districList=[NSMutableArray arrayWithArray:returnDict[#"data"]];
{
}
-(void)callforLLG:(NSString*)serviceName idForItem:(NSString*)idForItem
{
dispatch_async(dispatch_get_main_queue(), ^{
[self getIIL:idForItem];
});
}
- (void)viewDidLayoutSubviews
{
[profileScrollView setContentSize:CGSizeMake(self.view.frame.size.width, 700)];
}
- (IBAction)uploadPictureButtonTap:(UIButton *)sender
{
UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:#"Select option" delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:
#"Open Gallery",
#"Take Photo",
nil];
popup.tag = 1;
[popup showInView:[UIApplication sharedApplication].keyWindow];
}
- (IBAction)provinceButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
NSMutableArray *provinceNames=[NSMutableArray array];
for (NSMutableDictionary*pro in provinceList)
{
[provinceNames addObject:pro[#"province_name"]];
}
LGActionSheet *sheet=[[LGActionSheet alloc] initWithTitle:#"Select Province" buttonTitles:provinceNames cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil];
sheet.tagOfSheet=2;
sheet.heightMax=300;
sheet.delegate=self;
[sheet showAnimated:YES completionHandler:nil];
}
- (IBAction)districtButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
NSMutableArray *names=[NSMutableArray array];
for (NSMutableDictionary*pro in districList)
{
[names addObject:pro[#"district_name"]];
}
LGActionSheet *sheet=[[LGActionSheet alloc] initWithTitle:#"Select District" buttonTitles:names cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil];
sheet.heightMax=200;
sheet.tagOfSheet=3;
sheet.delegate=self;
[sheet showAnimated:YES completionHandler:nil];
}
- (IBAction)LLGButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
NSMutableArray *names=[NSMutableArray array];
for (NSMutableDictionary*pro in llgList)
{
[names addObject:pro[#"llg_name"]];
}
LGActionSheet *sheet=[[LGActionSheet alloc] initWithTitle:#"Select LLG" buttonTitles:names cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil];
sheet.heightMax=200;
sheet.tagOfSheet=4;
sheet.delegate=self;
[sheet showAnimated:YES completionHandler:nil];
}
- (IBAction)villageButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
}
- (IBAction)question1ButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
NSMutableArray *ques1=[NSMutableArray array];
for (NSMutableDictionary*pro in questions1Array)
{
[ques1 addObject:pro[#"question_name"]];
}
LGActionSheet *sheet=[[LGActionSheet alloc] initWithTitle:#"Select Question 1" buttonTitles:ques1 cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil];
sheet.tagOfSheet=5;
sheet.heightMax=300;
sheet.delegate=self;
[sheet showAnimated:YES completionHandler:nil];
}
- (IBAction)question2ButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
NSMutableArray *ques2=[NSMutableArray array];
for (NSMutableDictionary*pro in questions1Array)
{
[ques2 addObject:pro[#"question_name"]];
}
LGActionSheet *sheet=[[LGActionSheet alloc] initWithTitle:#"Select Question 2" buttonTitles:ques2 cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil];
sheet.tagOfSheet=6;
sheet.heightMax=300;
sheet.delegate=self;
[sheet showAnimated:YES completionHandler:nil];
}
- (IBAction)updateButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[selectedValues setObject:#"ios" forKey:#"request"];
[selectedValues setObject:[NSString stringWithFormat:#"%#",currentUser.user_id] forKey:#"user_id"];
[selectedValues setObject:postalAddressTextfield.text forKey:#"address"];
[selectedValues setObject:mobileTextfield.text forKey:#"user_mobile"];
[selectedValues setObject:question1Textfield.text forKey:#"user_answer_1"];
[selectedValues setObject:villageTextfield.text forKey:#"user_village"];
[GeneralWebservices webserviceCallWithData:selectedValues webserviceName:Webservice_ProfileUpdate dataToPost:imageData imageName:imageName OnCompletion:^(id returnDict, NSError *error) {
if ([returnDict[#"success"] intValue] == 1)
{
UIAlertView* alert = [[UIAlertView alloc] init];
[alert setTitle:#"Updated Successfully"];
[alert addButtonWithTitle:#"OK"];
[alert show];
}
else
{
UIAlertView* alert = [[UIAlertView alloc] init];
[alert setTitle:#"Updated Successfully"];
[alert addButtonWithTitle:#"OK"];
[alert show];
}
[MBProgressHUD hideAllHUDsForView:self.view animated:NO];
}];
}
- (IBAction)saveButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
}
- (void)actionSheet:(LGActionSheet *)actionSheet buttonPressedWithTitle:(NSString *)title index:(NSUInteger)index
{
dispatch_async(dispatch_get_main_queue(), ^{
if (actionSheet.tagOfSheet==2)
{
[selectedValues setObject:provinceList[index][#"province_id"] forKey:#"user_province"];
[provinceButton setTitle:provinceList[index][#"province_name"] forState:UIControlStateNormal];
[districList removeAllObjects];
[llgList removeAllObjects];
[districtButton setTitle:#"District *" forState:UIControlStateNormal];
[LLGButton setTitle:#"LLG *" forState:UIControlStateNormal];
[selectedValues removeObjectForKey:#"district"];
[selectedValues removeObjectForKey:#"llg"];
[self callforDistrict:#"get_district.php" idForItem:provinceList[index][#"province_id"]];
}
else if(actionSheet.tagOfSheet==3)
{
[selectedValues setObject:districList[index][#"id"] forKey:#"user_district"];
[districtButton setTitle:districList[index][#"district_name"] forState:UIControlStateNormal];
[llgList removeAllObjects];
[LLGButton setTitle:#"LLG *" forState:UIControlStateNormal];
[selectedValues removeObjectForKey:#"llg"];
[self callforLLG:#"get_llg.php" idForItem:districList[index][#"id"]];
}
else if(actionSheet.tagOfSheet==4)
{
[selectedValues setObject:llgList[index][#"id"] forKey:#"user_llg"];
[LLGButton setTitle:llgList[index][#"llg_name"] forState:UIControlStateNormal];
}
else if(actionSheet.tagOfSheet==5)
{
[selectedValues setObject:questions1Array[index][#"question_id"] forKey:#"user_question_1"];
[question1Button setTitle:questions1Array[index][#"question_name"] forState:UIControlStateNormal];
}
else if(actionSheet.tagOfSheet==6)
{
[selectedValues setObject:questions1Array[index][#"question_id"] forKey:#"user_question_2"];
[question2Button setTitle:questions1Array[index][#"question_name"] forState:UIControlStateNormal];
}
});
}
-(IBAction) returnTextField:(id)sender
{
CGRect frame = self.view.frame;
frame.origin.y = 0;
[UIView animateWithDuration:0.3 animations:^{
self.view.frame = frame;
}];
[self.view endEditing:YES];
}
- (BOOL)textFieldShouldEndEditing:(UITextField*)textField
{
return YES;
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField
{
[self animateTextField:textField up:NO];
[textField resignFirstResponder];
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self animateTextField:textField up:YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
[self animateTextField:textField up:NO];
}
- (void)actionSheet:(UIActionSheet *)popup clickedButtonAtIndex:(NSInteger)buttonIndex
{
switch (popup.tag) {
case 1: {
switch (buttonIndex) {
case 0:
[self openPhotoLibraryButton:self];
break;
case 1:
[self openCameraButton:self];
break;
default:
break;
}
break;
}
default:
break;
}
}
- (IBAction)openCameraButton:(id)sender
{
[self.view endEditing:YES];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
picker.allowsEditing = false;
[self presentViewController:picker animated:true completion:nil];
}
else{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Camera is not connected" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
- (IBAction)openPhotoLibraryButton:(id)sender
{
[self.view endEditing:YES];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
picker.allowsEditing = true;
[self presentViewController:picker animated:true completion:nil];
}
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissViewControllerAnimated:YES completion:nil];
imageData=[[NSData alloc]init];
if ([info[#"UIImagePickerControllerMediaType"] isEqualToString:#"public.image"])
{
UIImage *image = [info objectForKey:#"UIImagePickerControllerEditedImage"];
if (!image)
{
image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
}
NSURL *imagePath = [info objectForKey:#"UIImagePickerControllerReferenceURL"];
image=[SettingsClass rotateImageAppropriately:image];
NSString *imageNamewithformat = [imagePath lastPathComponent];
imageName=#"assets.jpg";
NSString *Imageformat = [imageNamewithformat substringFromIndex: [imageNamewithformat length] - 3];
if ([Imageformat isEqualToString:#"JPG"]||[Imageformat isEqualToString:#"jpg"]) {
imageData=UIImageJPEGRepresentation(image, 0.33f);
imageName=#"assets.jpg";
}
else if ([Imageformat isEqualToString:#"PNG"]||[Imageformat isEqualToString:#"png"])
{
imageData=UIImagePNGRepresentation(image);
imageName=#"assets.png";
}
else
{
imageData=UIImageJPEGRepresentation(image, 0.33f);
imageName=#"assets.jpg";
}
[profilePicImageView setImage:image];
}
}
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
CGPoint temp = [textField.superview convertPoint:textField.frame.origin toView:nil];
UIInterfaceOrientation orientation =
[[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationPortrait){
if(up) {
int moveUpValue = temp.y+textField.frame.size.height;
animatedDis = 264-(self.view.frame.size.height-moveUpValue-35);
}
}
else if(orientation == UIInterfaceOrientationPortraitUpsideDown) {
if(up) {
int moveUpValue = self.view.frame.size.height-temp.y+textField.frame.size.height;
animatedDis = 264-(self.view.frame.size.height-moveUpValue-35);
}
}
else if(orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
if(up) {
int moveUpValue = temp.y+textField.frame.size.height;
animatedDis = 352-(self.view.frame.size.height-moveUpValue-100);
}
}
else
{
if(up) {
int moveUpValue = temp.y+textField.frame.size.height;
animatedDis = 352-(768-moveUpValue-100);
}
}
if(animatedDis>0)
{
const int movementDistance = animatedDis;
const float movementDuration = 0.3f;
int movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: nil context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
if (orientation == UIInterfaceOrientationPortrait){
self.view.frame = CGRectOffset( self.view.frame, 0, movement);
}
else if(orientation == UIInterfaceOrientationPortraitUpsideDown) {
self.view.frame = CGRectOffset( self.view.frame, 0, movement);
}
else if(orientation == UIInterfaceOrientationLandscapeLeft) {
self.view.frame = CGRectOffset( self.view.frame, 0, movement);
}
else {
self.view.frame = CGRectOffset( self.view.frame, 0, movement);
}
[UIView commitAnimations];
}
}
- (IBAction)backtohomeview :(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)getdistdata:(NSString*)idForItem
{
self.view.userInteractionEnabled = NO;
NSString *strURL;
strURL = [NSString stringWithFormat:#"http://bullionscope.com/Gold_Phase3/webservices/get_district.php?request=ios&province_id=%#",idForItem];
NSDictionary *headers = #{ #"cache-control": #"no-cache",
#"postman-token": #"900e1577-4876-cd9a-d24c-cb0631b4a1fb" };
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
}
else
{
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *success = [[jsonDic objectForKey:#"success"]stringValue];
if (
[success isEqualToString:
#"1"])
{
districList=[NSMutableArray arrayWithArray:[jsonDic objectForKey:#"data"]];
dispatch_async(dispatch_get_main_queue(), ^{
self.view.userInteractionEnabled = YES;
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
self.view.userInteractionEnabled = YES;
});
}
}
}];
[dataTask resume];
}
-(void)getIIL:(NSString*)idForItem
{
self.view.userInteractionEnabled = NO;
NSString *strURL;
strURL = [NSString stringWithFormat:#"http://bullionscope.com/Gold_Phase3/webservices/get_llg.php?request=ios&district_id=%#",idForItem];
NSDictionary *headers = #{ #"cache-control": #"no-cache",
#"postman-token": #"900e1577-4876-cd9a-d24c-cb0631b4a1fb" };
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
}
else
{
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *success = [[jsonDic objectForKey:#"success"]stringValue];
if (
[success isEqualToString:
#"1"])
{
llgList=[NSMutableArray arrayWithArray:[jsonDic objectForKey:#"data"]];
dispatch_async(dispatch_get_main_queue(), ^{
self.view.userInteractionEnabled = YES;
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
self.view.userInteractionEnabled = YES;
});
}
}
}];
[dataTask resume];
}
-(void)get_register_data
{
self.view.userInteractionEnabled = NO;
NSString *strURL;
http://bullionscope.com/Gold_Phase3/webservices/get_all_province.php?request=ios
strURL = [NSString stringWithFormat:#"http://bullionscope.com/Gold_Phase3/webservices/get_all_province.php?request=ios"];
NSDictionary *headers = #{ #"cache-control": #"no-cache",
#"postman-token": #"900e1577-4876-cd9a-d24c-cb0631b4a1fb" };
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
}
else
{
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *success = [[jsonDic objectForKey:#"success"]stringValue];
if (
[success isEqualToString:
#"1"])
{
provinceList=[NSMutableArray arrayWithArray:[jsonDic objectForKey:#"data"]];
dispatch_async(dispatch_get_main_queue(), ^{
self.view.userInteractionEnabled = YES;
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
self.view.userInteractionEnabled = YES;
});
}
}
}];
[dataTask resume];
}
#end

NSURLConnect works only 1 time

I'm trying to do a request but it works only in the first time....
Here is my code:
NSArray *infos = [rows objectAtIndex:indexPath.row];
NSString *thumbPath = thePath;
NSURLRequest *thumbRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:thumbPath]cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
self->thumbConnection = [[NSURLConnection alloc] initWithRequest:thumbRequest
delegate:self
startImmediately:YES];
self->thumbData = [[NSMutableData alloc]init];
when receive Response
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if (self->thumbData == nil) {
self->thumbData = [[NSMutableData alloc]init];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
self.thumbImage.image = [UIImage imageWithData:self->thumbData];
self.thumbActivityView.hidden = YES;
self->thumbData = nil;
}
when didFinishDownloading:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
self.thumbImage.image = [UIImage imageWithData:self->thumbData];
self.thumbActivityView.hidden = YES;
[self->thumbData release];
self->thumbData = nil;
}
when timeout or other erros method:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[self->thumbData release];
self->thumbData = nil;
self.thumbActivityView.hidden = YES;
[thumbConnection release];
self->thumbConnection = nil;
}
Don't allocate it again if it's non-nil. Better still allocate it in your object's init method and release it in your object's dealloc method

MBProgressHud and SDWebImagePrefetcher

I'm trying to show a custom MBProgressHUD while downloading a list of URLs with SDWebImagePrefetcher using NSURLConnection methods.
SDWebImagePrefetcher has a method that, when called, shows in console the progress of the images download.
Now, i would like to show that NSLog progress in the custom MBProgressHUD and I would like the HUD to stay on screen until the process is done, but I don't know how to do it and plus, when my NSURLConnection methods are called, it shows the initial HUD (Connnecting), then quickly jumps to "Complete", even if the images still needs to be downloaded.
Here's my code:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
HUD.mode = MBProgressHUDModeDeterminate;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
HUD.labelText = #"Loading";
HUD.detailsLabelText = #"Downloading contents..."; //here, i would like to show the progress of the download, but it seems to jump this part
HUD.dimBackground = YES;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//arr = array which holds a plist
NSMutableArray *array = [[[NSMutableArray alloc]init]autorelease];
for (NSDictionary *dict in arr) {
for (NSDictionary *val in [dict valueForKey:STR_ROWS]) {
[array addObject:[val objectForKey:#"image"]];
}
}
[prefetcher prefetchURLs:array];
HUD.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"checkmark.png"]] autorelease];
HUD.mode = MBProgressHUDModeCustomView;
HUD.labelText = NSLocalizedString(#"Completed",#"Completed!");
HUD.detailsLabelText = nil;
HUD.dimBackground = YES;
[HUD hide:YES afterDelay:2];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[HUD hide:YES];
UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:#"Connection Failed message:[NSString stringWithFormat:#"Connection to the remote server failed with error:\n %#\n Try again in a while"),[error localizedDescription]] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease];
[alertView show];
}
I tried to look into the examples, but didn't find out how to do what i want to do.
EDIT
HUD Setup:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0){
[alertView dismissWithClickedButtonIndex:0 animated:YES];
}
else{
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus) {
case NotReachable:
{
//not reachable
break;
}
case (ReachableViaWWAN):
{
//reachable but not with the needed mode
break;
}
case (ReachableViaWiFi):{
HUD = [[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES]retain];
HUD.delegate = self;
HUD.dimBackground = YES;
HUD.labelText = #"Connecting...";
NSURL *URL = [NSURL URLWithString:#"http://mywebsite.com/myPlist.plist"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
[connection release];
break;
}
default:
break;
}
}
}
Any ideas?
In connection:didReceiveResponse: you must record how large the download is,
for example in self.responseSize. Then, in connection:didReceiveData: you
must append the data you just got to the data you previously got, and update the progress:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
HUD.mode = MBProgressHUDModeDeterminate;
HUD.labelText = #"Loading";
HUD.detailsLabelText = #"Downloading contents...";
HUD.dimBackground = YES;
// Define responseSize somewhere...
responseSize = [response expectedContentLength];
myData = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[myData appendData:data];
HUD.progress = (float)myData.length / responseSize;
}

Loading and changing images asynchronous

Im loading 4 images from a website asynchronous,and after the loading i change them with a timer,but looks like on the array of the images is always the first image,when i change to another position of the array it contains the same image,dont change at all...
- (void)viewDidLoad
{
[super viewDidLoad];
[self getImages];
}
-(void)getImages
{
receivedData = [[NSMutableData alloc]init];
myImages = [[NSMutableArray alloc]init];
myImagesAdresses = [[NSMutableArray alloc]initWithCapacity:5];
[myImagesAdresses addObject:#"adress/Images/3.png"];
[myImagesAdresses addObject:#"adress/Images/2.png"];
[myImagesAdresses addObject:#"adress/Images/1.png"];
[myImagesAdresses addObject:#"adress/Images/0.png"];
[self loadNextImage];
}
-(void)loadNextImage
{
if([myImagesAdresses count])
{
NSURL * imageURL = [NSURL URLWithString:[myImagesAdresses lastObject]];
NSURLRequest * myRequest = [NSURLRequest requestWithURL:imageURL];
[[NSURLConnection alloc]initWithRequest:myRequest delegate:self];
NSLog(#"Start load URL %#",imageURL);
}
else {
[self.theImage setImage:[myImages objectAtIndex:2]];
[self changeImage];
NSLog(#"No More Images to Load");
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[myImages addObject:[UIImage imageWithData:[NSData dataWithData:receivedData]]];
[connection release];
connection = nil;
NSLog(#"Image from %# loaded",[myImagesAdresses lastObject]);
[myImagesAdresses removeLastObject];
[self loadNextImage];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
connection =nil;
NSLog(#"Image from %# not loaded", [myImagesAdresses lastObject]);
[myImagesAdresses removeLastObject];
[self loadNextImage];
}
and the code to change the image:
-(void)changeImage
{
SEL selectorToCall = #selector(change: );
NSMethodSignature *methodSignature = [[self class] instanceMethodSignatureForSelector:selectorToCall];
NSInvocation * invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
[invocation setTarget:self];
[invocation setSelector:selectorToCall];
NSTimer * newTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:YES];
self.paintingTimer = newTimer;
}
- (void) change:(NSTimer *)paramTimer
{
static NSInteger currentElement = 0;
if(++currentElement == [myImages count]) currentElement = 0;
[self.theImage setImage:[myImages objectAtIndex:currentElement]];
}
- (void) stopPainting
{
if (self.paintingTimer != nil){
[self.paintingTimer invalidate];
}
}
I dont getting any error,but the image simply dont change...
It looks like receivedData is an ivar that you repeatedly append to, but it never gets cleared. So after the first image is received, the second image is appended to it, etc.
After this line, you should empty receivedData:
[myImages addObject:[UIImage imageWithData:[NSData dataWithData:receivedData]]];
You should add this line of code after:
[myImages addObject:[UIImage imageWithData:[NSData dataWithData:receivedData]]];
like this:
[myImages addObject:[UIImage imageWithData:[NSData dataWithData:receivedData]]];
[receivedData setData:nil];

Returned web service data not populating tableview

Hey, I cant seem why this code is not working? I am trying to add my returned data from a web service into the uitableview, however failing miserably. The table shows up blank everytime. It seems it doesnt like the cellForRowAtIndexPath method. But honestly I am not sure. I cant spot it for nothing. Please help. Thanks!
#import "RSSTableViewController.h"
#implementation RSSTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
if (self = [super initWithStyle:style]) {
songs = [[NSMutableArray alloc] init];
}
return self;
}
- (void)loadSongs
{
[songs removeAllObjects];
[[self tableView] reloadData];
// Construct the web service URL
NSURL *url =[NSURL URLWithString:#"http://localhost/get_params"];
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
if (connectionInProgress) {
[connectionInProgress cancel];
[connectionInProgress release];
}
[xmlData release];
xmlData = [[NSMutableData alloc] init];
connectionInProgress = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self loadSongs];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[xmlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];
songs = [responseString componentsSeparatedByString:#","];
newSongs = [[NSMutableArray alloc] init];
for(int i=0; i < [songs count]; i++) {
[newSongs addObject:[songs:i]]);
}
[songs autorelease];
[[self tableView] reloadData];
//
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
[connectionInProgress release];
connectionInProgress = nil;
[xmlData release];
xmlData = nil;
NSString *errorString = [NSString stringWithFormat:#"Fetch failed: %#",
[error localizedDescription]];
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:errorString
delegate:nil
cancelButtonTitle:#"OK"
destructiveButtonTitle:nil
otherButtonTitles:nil];
[actionSheet showInView:[[self view] window]];
[actionSheet autorelease];
[[self tableView] reloadData];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[super dealloc];
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [newSongs count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"UITableViewCell"] autorelease];
}
[[cell textLabel] setText:[newSongs objectAtIndex:[indexPath row]]];
return cell;
}
#end
It appears you're ignoring warning messages, which is a no-no in Objective-C. The following code can't possibly work:
[newSongs addObject:[songs:i]]
What you probably meant to write was something like this:
[newSongs addObject:[songs objectAtIndex:i]]
But instead of doing all this:
newSongs = [[NSMutableArray alloc] init];
for(int i=0; i < [songs count]; i++) {
[newSongs addObject:[songs:i]]);
}
why not just do this?
newSongs = [songs mutableCopy];