This question has been asked many times, but I have tried all of the options, and none of them seem to work. In my ios app, whenever I try to make an alert view, this happens:
http://i61.tinypic.com/kalnk2.png
I don't know what to do. When I click ok, I get this error: (This is the entire error)
http://pastebin.com/raw.php?i=BEeGbjJ8
My code is:
#implementation AJSettingsViewController
-(NSString*) dataFilePath{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:FILENAME];
}
-(void) saveFile{
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:country];
[array addObject:state];
[array addObject:town];
[array addObject:zipcode];
[array addObject:name];
[array writeToFile:[self dataFilePath] atomically:YES];
//[array dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
zipcodetextfield.translatesAutoresizingMaskIntoConstraints = NO;
[view setTranslatesAutoresizingMaskIntoConstraints:NO];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)zipcodelookup:(id)sender{
[zipcodetextfield resignFirstResponder];
zipcodetextfield.translatesAutoresizingMaskIntoConstraints = NO;
zipcode = zipcodetextfield.text;
if(zipcode.length >0){
NSString *url = [NSString stringWithFormat:#"http://ziptasticapi.com/%#",zipcode];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString: url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
[connection start];
NSError *noconnection;
NSString *htmlpage = [NSString stringWithContentsOfURL:[NSURL URLWithString: url] encoding:NSASCIIStringEncoding
error:&noconnection];
//NSLog(htmlpage);
if ([htmlpage rangeOfString:#"error"].location == NSNotFound) {
htmlpage = [htmlpage stringByReplacingOccurrencesOfString:#"{" withString:#""];
htmlpage = [htmlpage stringByReplacingOccurrencesOfString:#"}" withString:#""];
htmlpage = [htmlpage stringByReplacingOccurrencesOfString:#":" withString:#""];
htmlpage = [htmlpage stringByReplacingOccurrencesOfString:#"\"" withString:#""];
htmlpage = [htmlpage stringByReplacingOccurrencesOfString:#"country" withString:#""];
htmlpage = [htmlpage stringByReplacingOccurrencesOfString:#"city" withString:#""];
htmlpage = [htmlpage stringByReplacingOccurrencesOfString:#"state" withString:#""];
NSLog(htmlpage);
} else {
zipcodetextfield.text = #"";
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"We were unable to locate this zipcode. Please try again"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
message.translatesAutoresizingMaskIntoConstraints = NO;
[message show];
}
}else{
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Please Enter A ZipCode"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
message.translatesAutoresizingMaskIntoConstraints = NO;
[message show];
}
}
-(IBAction)exitkeyboard:(id)sender{
[zipcodetextfield resignFirstResponder];
}
#end
I am at absolute wits end here, so any help would be greatly appreciated.
Thanks
message.translatesAutoresizingMaskIntoConstraints = NO;
Do not set this for UIAlertView - the alert view and its private manager will decide how its layout works.
Try to use delegate:self instead of nil and in your .h file, add UIAlertViewDelegate so that it looks like this:
#interface AJSettingsViewController : UIViewController <UIAlertViewDelegate>
Try to use UIAlertController:
UIAlertController *myAlertController = [UIAlertController
alertControllerWithTitle:#"Title"
message:#"Message"
preferredStyle:UIAlertControllerStyleAlert];
with buttons:
UIAlertAction *myCancelAction = [UIAlertAction
actionWithTitle:NSLocalizedString(#"Cancel", #"Cancel")
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action)
{
NSLog(#"Cancel action");
[self someGreatActionWithIndex:0];
}];
UIAlertAction *myOkAction = [UIAlertAction
actionWithTitle:NSLocalizedString(#"OK", #"OK")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
NSLog(#"OK action");
[self someGreatActionWithIndex:1];
}];
[myAlertController addAction:myCancelAction];
[myAlertController addAction:myOkAction];
Hope this helps!
Related
I am trying to Parse SOAP data [using NSURLConnection, as I am not getting to use NSURLSession]
and trying to display that on multiple UILabels
Issue is - when printing response data on Console it is printed quickly, but It is taking too much time (50-60 sec) to display on labels.
Please suggest me any possible way to display data quickly, Here is my code
#pragma mark - post data function
-(void)getEmployeeData{
//Renewed CODE
loginData = [[NSMutableData alloc]init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
NSString *methodName = #"Get_Data";
//SOAP Start
[connectionManagerObject getStartSoapData:loginData :methodName];
//SOAP Body
NSString *passedUserID = [[NSUserDefaults standardUserDefaults] objectForKey:#"StoredUserID"];
// NSLog(#"passed UserID : %#",passedUserID);
NSString *passedPassword = [[NSUserDefaults standardUserDefaults] objectForKey:#"StoredPassword"];
// NSLog(#"passed Password : %#",passedPassword);
NSString *userIdValue = [NSString stringWithFormat:#"<EMP_NAME>%#</EMP_NAME>",passedUserID];
NSString *passwordValue = [NSString stringWithFormat:#"<EMP_PASSWORD>%#</EMP_PASSWORD>",passedPassword];
[loginData appendData:[userIdValue dataUsingEncoding:NSUTF8StringEncoding]];
[loginData appendData:[passwordValue dataUsingEncoding:NSUTF8StringEncoding]];
//SOAP End
[connectionManagerObject getEndSoapData:loginData :methodName];
//SOAP Request
[connectionManagerObject getRequest:loginData :request :[NSURL URLWithString:HOST_URL] :methodName];
//Start connection
[self startConnectionWithRequest:request];
}
#pragma mark - Start Connection
-(void)startConnectionWithRequest:(NSMutableURLRequest *)URLRequest
{
loginConnection = [[NSURLConnection alloc]initWithRequest:URLRequest delegate:self startImmediately:YES];
if (loginConnection)
{
// NSLog(#" \n\n Successfully connected with server !!! ");
}
else
{
// NSLog(#" \n\n Connection Not Established !!! ");
}
[loginConnection start];
}
#pragma mark - Connection Delegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[loginData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data
{
[loginData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Warning !" message:#"Please Check your internet connection" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSMutableString alloc]initWithData:loginData encoding:NSUTF8StringEncoding];
responseString = [responseString substringFromIndex:[responseString rangeOfString:#"<Get_DataResult>"].location + [#"<Get_DataResult>" length]];
responseString = [responseString substringToIndex:[responseString rangeOfString:#"</Get_DataResult>"].location];
// NSLog(#"Response string : %#",responseString);
if ([responseString containsString:#"^"])
{
[self displayProfileData:responseString];
}
else
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Warning !" message:#"Please Check your login credentials" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
[self.navigationController popViewControllerAnimated:NO];
}
}
#pragma mark - Display data function
-(void)displayProfileData:(NSString *)storedEmployeeResponse
{
[NSThread detachNewThreadSelector:#selector(start) toTarget:self withObject:nil];
//GCD CODE
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// do my time consuming task and everytime it wants to update the UI,
// it should dispatch that back to the main queue, e.g.
NSArray *passEmpDataArray = [[NSArray alloc]init];
passEmpDataArray = [storedEmployeeResponse componentsSeparatedByString:#"^"];
NSString *empCodeStr = [passEmpDataArray objectAtIndex:0];
NSString *empNameStr = [passEmpDataArray objectAtIndex:1];
NSString *empDeptStr = [passEmpDataArray objectAtIndex:3];
NSString *empDesgStr = [passEmpDataArray objectAtIndex:5];
NSString *empGenderStr = [passEmpDataArray objectAtIndex:4];
NSString *empDojStr = [passEmpDataArray objectAtIndex:6];
NSString *empDobStr = [passEmpDataArray objectAtIndex:7];
NSString *empEmailStr = [passEmpDataArray objectAtIndex:9];
NSString *empMobileStr = [passEmpDataArray objectAtIndex:8];
dispatch_sync(dispatch_get_main_queue(), ^{
// update the UI accordingly
_empCodeLabel.text = [NSString stringWithFormat:#"Emp Code %#",empCodeStr];
_empNameLabel.text = [NSString stringWithFormat:#"Emp Name %#",empNameStr];
_empDeptLabel.text = [NSString stringWithFormat:#"Emp Dept %#",empDeptStr];
_empDesgLabel.text = [NSString stringWithFormat:#"Emp Desg %#",empDesgStr];
_empGenderLabel.text = [NSString stringWithFormat:#"Gender %#",empGenderStr];
_empDojLabel.text = [NSString stringWithFormat:#"DOJ %#",empDojStr];
_empDobLabel.text = [NSString stringWithFormat:#"DOB %#",empDobStr];
_empEmailIdLabel.text = [NSString stringWithFormat:#"Email ID %#",empEmailStr];
_empMobileNo.text = [NSString stringWithFormat:#"Mobile No %#",empMobileStr];
NSString *tempUrl = [NSString stringWithFormat:Image_URL,empCodeStr];
NSURL *url = [NSURL URLWithString:tempUrl];
loginData = [NSMutableData dataWithContentsOfURL:url];
_profilePic.image = [UIImage imageWithData:loginData];
[self stop];
});
});
}
#pragma mark - post data function
-(void)getEmployeeData
{
//Renewed CODE
loginData = [[NSMutableData alloc]init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
NSString *methodName = #"Get_Data";
//SOAP Start
[connectionManagerObject getStartSoapData:loginData :methodName];
//SOAP Body
NSString *passedUserID = [[NSUserDefaults standardUserDefaults] objectForKey:#"StoredUserID"];
// NSLog(#"passed UserID : %#",passedUserID);
NSString *passedPassword = [[NSUserDefaults standardUserDefaults] objectForKey:#"StoredPassword"];
// NSLog(#"passed Password : %#",passedPassword);
NSString *userIdValue = [NSString stringWithFormat:#"<EMP_NAME>%#</EMP_NAME>",passedUserID];
NSString *passwordValue = [NSString stringWithFormat:#"<EMP_PASSWORD>%#</EMP_PASSWORD>",passedPassword];
[loginData appendData:[userIdValue dataUsingEncoding:NSUTF8StringEncoding]];
[loginData appendData:[passwordValue dataUsingEncoding:NSUTF8StringEncoding]];
//SOAP End
[connectionManagerObject getEndSoapData:loginData :methodName];
//SOAP Request
[connectionManagerObject getRequest:loginData :request :[NSURL URLWithString:HOST_URL] :methodName];
//Start connection
[self startConnectionWithRequest:request];
}
#pragma mark - Start Connection
-(void)startConnectionWithRequest:(NSMutableURLRequest *)URLRequest
{
loginConnection = [[NSURLConnection alloc]initWithRequest:URLRequest delegate:self startImmediately:YES];
if (loginConnection)
{
// NSLog(#" \n\n Successfully connected with server !!! ");
}
else
{
// NSLog(#" \n\n Connection Not Established !!! ");
}
[loginConnection start];
}
#pragma mark - Connection Delegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[loginData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data
{
[loginData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Warning !" message:#"Please Check your internet connection" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSMutableString alloc]initWithData:loginData encoding:NSUTF8StringEncoding];
responseString = [responseString substringFromIndex:[responseString rangeOfString:#"<Get_DataResult>"].location + [#"<Get_DataResult>" length]];
responseString = [responseString substringToIndex:[responseString rangeOfString:#"</Get_DataResult>"].location];
// NSLog(#"Response string : %#",responseString);
if ([responseString containsString:#"^"])
{
[self displayProfileData:responseString];
}
else
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Warning !" message:#"Please Check your login credentials" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
[self.navigationController popViewControllerAnimated:NO];
}
}
#pragma mark - Display data function
-(void)displayProfileData:(NSString *)storedEmployeeResponse
{
[NSThread detachNewThreadSelector:#selector(start) toTarget:self withObject:nil];
//GCD CODE
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// do my time consuming task and everytime it wants to update the UI,
// it should dispatch that back to the main queue, e.g.
NSArray *passEmpDataArray = [[NSArray alloc]init];
passEmpDataArray = [storedEmployeeResponse componentsSeparatedByString:#"^"];
NSString *empCodeStr = [passEmpDataArray objectAtIndex:0];
NSString *empNameStr = [passEmpDataArray objectAtIndex:1];
NSString *empDeptStr = [passEmpDataArray objectAtIndex:3];
NSString *empDesgStr = [passEmpDataArray objectAtIndex:5];
NSString *empGenderStr = [passEmpDataArray objectAtIndex:4];
NSString *empDojStr = [passEmpDataArray objectAtIndex:6];
NSString *empDobStr = [passEmpDataArray objectAtIndex:7];
NSString *empEmailStr = [passEmpDataArray objectAtIndex:9];
NSString *empMobileStr = [passEmpDataArray objectAtIndex:8];
dispatch_sync(dispatch_get_main_queue(), ^{
// update the UI accordingly
_empCodeLabel.text = [NSString stringWithFormat:#"Emp Code %#",empCodeStr];
_empNameLabel.text = [NSString stringWithFormat:#"Emp Name %#",empNameStr];
_empDeptLabel.text = [NSString stringWithFormat:#"Emp Dept %#",empDeptStr];
_empDesgLabel.text = [NSString stringWithFormat:#"Emp Desg %#",empDesgStr];
_empGenderLabel.text = [NSString stringWithFormat:#"Gender %#",empGenderStr];
_empDojLabel.text = [NSString stringWithFormat:#"DOJ %#",empDojStr];
_empDobLabel.text = [NSString stringWithFormat:#"DOB %#",empDobStr];
_empEmailIdLabel.text = [NSString stringWithFormat:#"Email ID %#",empEmailStr];
_empMobileNo.text = [NSString stringWithFormat:#"Mobile No %#",empMobileStr];
NSString *tempUrl = [NSString stringWithFormat:Image_URL,empCodeStr];
NSURL *url = [NSURL URLWithString:tempUrl];
loginData = [NSMutableData dataWithContentsOfURL:url];
_profilePic.image = [UIImage imageWithData:loginData];
[self stop];
});
});
}
I have a ViewController which has two segues and I want that segue to present viewcontroller after fetching data from URL. So I have kept preparesegueWithIdentifier in connectionDidFinishLoading method.
But I am able to show only first viewcontroller.
I want that both segues works properly.
#import "specialistquery.h"
#import "FitnessView.h"
#import "askCall.h"
#import "Header.h"
#interface specialistquery ()<UITextFieldDelegate,UITextViewDelegate>
{
NSMutableData *responseData;
UIAlertView *alert;
}
#end
#implementation specialistquery
#synthesize title,discription,title1,CallBackBtn,SubmitBtn;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
dataArray = [[NSArray alloc]initWithObjects:#"Yoga Specialist", #"Dietician", #"Fitness Specialist", #"Homeopathic", #"Ayurvedic Specialist", nil];
UIPickerView *picker = [[UIPickerView alloc]init];
picker.delegate=self;
picker.dataSource=self;
[picker setShowsSelectionIndicator:YES];
[self.selectspecs setInputView:picker];
//toolbar
UIToolbar *toolbar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
[toolbar setTintColor:[UIColor grayColor]];
UIBarButtonItem *doneBtn=[[UIBarButtonItem alloc]initWithTitle:#"Done" style:UIBarButtonItemStylePlain target:self action:#selector(showSelectedDate)];
UIBarButtonItem *space=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[toolbar setItems:[NSArray arrayWithObjects: space, doneBtn,nil]];
[self.selectspecs setInputAccessoryView:toolbar];
[self.title1 setInputAccessoryView:toolbar];
[self.discription setInputAccessoryView:toolbar];
}
-(void)showSelectedDate
{
[self.selectspecs resignFirstResponder];
[self.title1 resignFirstResponder];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"good"]) {
FitnessView *spec = [segue destinationViewController];
spec.str = _selectspecs.text;
}
if ([segue.identifier isEqualToString:#"callback"]) {
askCall *spec = [segue destinationViewController];
spec.str = _selectspecs.text;
}
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [dataArray count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [dataArray objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
self.selectspecs.text = [dataArray objectAtIndex:row];
}
- (IBAction)DisKey:(id)sender {
[self.selectspecs resignFirstResponder];
[self.title1 resignFirstResponder];
[self.discription resignFirstResponder];
}
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
{
if ([identifier isEqualToString:#"good"])
{
if ([title1.text isEqualToString:#""] || [discription.text isEqualToString:#""] || [_selectspecs.text isEqualToString:#""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oppss!!!" message:#"ALL FIELDS MUST BE FILLED" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil ];
[alert show];
return NO;
}
else
{
NSDate *todayDate = [NSDate date]; // get today date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // here we create NSDateFormatter object for change the Format of date..
[dateFormatter setDateFormat:#"dd-MM-yyyy"]; //Here we can set the format which we need
NSString *convertedDateString = [dateFormatter stringFromDate:todayDate];// here convert date in
NSString *url;
url=#"http://www.bha.com/mDru/index.php";
const char *bytes = [[NSString stringWithFormat:#"question=%#&description=%#&createddate=%#&createdby=iPhone&userid=519&tag=storequestion",title1.text,discription.text,convertedDateString ] UTF8String];
NSURL *url1 = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url1];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
}
else if ([identifier isEqualToString:#"callback"])
{
if ([title1.text isEqualToString:#""] || [discription.text isEqualToString:#""] || [_selectspecs.text isEqualToString:#""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oppss!!!" message:#"ALL FIELDS MUST BE FILLED" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil ];
[alert show];
return NO;
}
else
{
NSDate *todayDate = [NSDate date]; // get today date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // here we create NSDateFormatter object for change the Format of date..
[dateFormatter setDateFormat:#"dd-MM-yyyy"]; //Here we can set the format which we need
NSString *convertedDateString = [dateFormatter stringFromDate:todayDate];// here convert date in
NSString *url;
url=#"http://www.bha.com/mDru/index.php";
const char *bytes = [[NSString stringWithFormat:#"question=%#&description=%#&createddate=%#&createdby=iPhone&userid=519&tag=storequestion",title1.text,discription.text,convertedDateString ] UTF8String];
NSURL *url1 = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url1];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
}
return NO;
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData = [[NSMutableData alloc] init];
alert = [[UIAlertView alloc] initWithTitle:#"Please Wait..." message:#"Saving Data" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
[alert show];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[alert dismissWithClickedButtonIndex:0 animated:YES];
UIAlertView *nsjsdn = [[UIAlertView alloc] initWithTitle:nil message:#"Internet connection problem" delegate:self cancelButtonTitle:#"Exit" otherButtonTitles:nil, nil];
[nsjsdn show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *teststr=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSString *str1234 = [teststr stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSLog(#"Response is %# %lul",str1234,(unsigned long)
[str1234 length]);
[alert dismissWithClickedButtonIndex:0 animated:YES];
[self performSegueWithIdentifier:#"good" sender:self];
[self performSegueWithIdentifier:#"callback" sender:self];
}
#end
If you do this, I believe you should get the result you require.
Make IBOutlets button1 and button2 for your buttons and IBAction methods for your buttons and set its selected property to YES.
- (IBAction)button1Clicked:(id)sender
{
button1.selected = YES;
if (button2.selected)
{
// This is done so that both buttons do not appear as clicked at the same time
button2.selected = NO;
}
}
- (IBAction)button2Clicked:(id)sender
{
button2.selected = YES;
if (button1.selected)
{
// This is done so that both buttons do not appear as clicked at the same time
button1.selected = NO;
}
}
After this is done, in your connectionDidFinishLoading method do this check.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *teststr=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSString *str1234 = [teststr stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSLog(#"Response is %# %lul",str1234,(unsigned long)
[str1234 length]);
[alert dismissWithClickedButtonIndex:0 animated:YES];
if (button1.selected)
{
[self performSegueWithIdentifier:#"good" sender:self];
}
else if (button2.selected)
{
[self performSegueWithIdentifier:#"callback" sender:self];
}
}
Hope it helps.
I have integrated google plus in my ios app ,I am able to get access token.I have used authentication flow to integrate google plus.So now after getting access token how can i get user profile details like username, email id, profile pic etc?
My code to get access token is as below:
-(IBAction)btnGooglePlusClicked:(UIButton *)sender
{
IBwebView.hidden = FALSE;
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%#&redirect_uri=%#&scope=%#&data-requestvisibleactions=%#",GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CALL_BACK_URL,GOOGLE_PLUS_SCOPE,GOOGLE_PLUS_VISIBLE_ACTIONS];
[IBwebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
// [indicator startAnimating];
if ([[[request URL] host] isEqualToString:#"localhost"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"code"]) {
verifier = [keyValue objectAtIndex:1];
NSLog(#"verifier %#",verifier);
break;
}
}
if (verifier) {
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CLIENT_SECRET,GOOGLE_PLUS_CALL_BACK_URL];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [[NSMutableData alloc] init];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
NSLog(#"verifier %#",receivedData);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"%#", error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
SBJsonParser *jResponse = [[SBJsonParser alloc]init];
NSDictionary *tokenData = [jResponse objectWithString:response];
// WebServiceSocket *dconnection = [[WebServiceSocket alloc] init];
// dconnection.delegate = self;
NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#", [tokenData objectForKey:#"refresh_token"], self.isLogin];
// NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#",[tokenData accessToken.secret,self.isLogin];
// [dconnection fetch:1 withPostdata:pdata withGetData:#"" isSilent:NO];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Google Access TOken"
message:pdata
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
I feel the the method you are using will not help to get the profile detail.
I suggest to use the proper method which ensures the best results.
Please check this out : https://developers.google.com/+/mobile/ios/
This will surely help you to get required outcome.
I need to show a UIActivityIndicator while i am waiting for response from the web service. Where exactly do i put the code for it?? It does not work this way. the activity indicator does not show up.
Do i need to use asynchronous request in order to show it??
-(void)callWebService
{
[self.customercareSearchbar resignFirstResponder];
[self.SRResultDictionary removeAllObjects];
NSLog(#"web service called");
NSString *srn = _SRNumber;
NSString *serviceURL = [NSString stringWithFormat:#"https://abcdef...];
#try {
UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:activity];
activity.center = self.view.center;
[self.view bringSubviewToFront:loadView];
activity.hidesWhenStopped = YES;
[activity setHidden:NO];
[activity startAnimating];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
NSURLResponse *serviceResponse = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];
[activity stopAnimating];
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
if(!parsedData)
{
NSLog(#"data not parsed");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[self.customerCareTableView setHidden:YES];
}
else
{
NSLog(#"parsed");
NSLog(#"parsed.. the size is %lu", (unsigned long)[parsedData count]);
NSLog(#"%#", parsedData);
NSString *status = [parsedData objectForKey:#"ns:Status"];
NSLog(#"the status is %#", status);
if([status isEqualToString:#"Success"])
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if([[prefs objectForKey:#"SwitchState"] isEqualToString:#"OFF"])
{
//do nothing
}
else
{
[self saveNumberInDatabase:srn];
}
NSMutableDictionary *third = [parsedData objectForKey:#"ListOfXrxLvServiceRequest"];
NSLog(#"internal dict is %#", third);
self.SRResultDictionary = [third objectForKey:#"ServiceRequest"];
[self.customerCareTableView reloadData];
[self.customerCareTableView setHidden:NO];
}
else if([status isEqualToString:#"Record Not Found"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Invalid Entry" message:#"Please enter a valid Service Request Number" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[self.customerCareTableView setHidden:YES];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[self.customerCareTableView setHidden:YES];
}
}
}
#catch (NSException *exception)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NULL message:#"Problem In Network Connection. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[self.customerCareTableView setHidden:YES];
}
#finally {
}
}
Yes, problem is the Synchronous request.
If it is fine to send ASynchronous request then try doing this.
[NSURLConnection sendAsynchronousRequest:request queue:nil completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// stop activity
// write other code you want to execute
}];
I found MBProgressHUD is best indicator and you can use is simply in your starting of method call like
dispatch_async(dispatch_get_main_queue(), ^{
if(!HUD) HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.view addSubview:HUD];
HUD.delegate = self;
HUD.userInteractionEnabled = NO;
HUD.labelText = #"Saving your Preferences...";
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
[HUD show:YES];
});
and in your finally block you can hide this like
dispatch_async(dispatch_get_main_queue(), ^{
[HUD hide:YES];
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
});
//.h file
#interface ViewController : UIViewController
{
UIActivityIndicatorView *activityIndicator;
BOOL showingActivityIndicator;
}
#property(nonatomic) BOOL showingActivityIndicator;
#property(nonatomic) UIActivityIndicatorView *activityIndicator;
#end
//.m file
#synthesize showingActivityIndicator,activityIndicator;
///// Call this method in viewDidLoad
-(void)initializeClass
{
self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
self.activityIndicator.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;
self.activityIndicator.hidesWhenStopped = YES;
[self layoutSubviews];
}
-(void)layoutSubviews
{
CGRect activityIndicatorFrame = self.activityIndicator.frame;
activityIndicatorFrame.origin.x = (self.view.frame.size.width - self.activityIndicator.frame.size.width) / 2;
activityIndicatorFrame.origin.y = (self.view.frame.size.height - self.activityIndicator.frame.size.height) / 2;
self.activityIndicator.frame = activityIndicatorFrame;
[self.view addSubview:self.activityIndicator];
}
-(void)setShowingActivityIndicator:(BOOL)showingActivityIndicators
{
if (showingActivityIndicators) {
[self.activityIndicator startAnimating];
} else {
[self.activityIndicator stopAnimating];
}
showingActivityIndicator= showingActivityIndicators;
}
-(void)dummyButtonAction // you button action to call service
{
[self setShowingActivityIndicator:YES];
[self performSelector:#selector(callWebService) withObject:nil afterDelay:0.3];
// [self callWebService];
}
-(void)callWebService
{
[self.view endEditing:YES]; // this statement will make sure keyboard is resigned
//[self.SRResultDictionary removeAllObjects];
NSLog(#"web service called");
NSString *srn = _SRNumber;
NSString *serviceURL = [NSString stringWithFormat:#"https://abcdef...];
#try {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
NSURLResponse *serviceResponse = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
if(!parsedData)
{
NSLog(#"data not parsed");
[self ShowAlertViewWithTitleString:#"ERROR":#"Problem in Network. Please Try Again!"];
[self.customerCareTableView setHidden:YES];
}
else
{
NSLog(#"parsed");
NSLog(#"parsed.. the size is %lu", (unsigned long)[parsedData count]);
NSLog(#"%#", parsedData);
NSString *status = [parsedData objectForKey:#"ns:Status"];
NSLog(#"the status is %#", status);
if([status isEqualToString:#"Success"])
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if([[prefs objectForKey:#"SwitchState"] isEqualToString:#"OFF"])
{
//do nothing
}
else
{
[self saveNumberInDatabase:srn];
}
NSMutableDictionary *third = [parsedData objectForKey:#"ListOfXrxLvServiceRequest"];
NSLog(#"internal dict is %#", third);
self.SRResultDictionary = [third objectForKey:#"ServiceRequest"];
[self.customerCareTableView reloadData];
[self.customerCareTableView setHidden:NO];
}
else if([status isEqualToString:#"Record Not Found"])
{
[self ShowAlertViewWithTitleString:#"Invalid Entry":#"Please enter a valid Service Request Number"];
[self.customerCareTableView setHidden:YES];
}
else
{
[self ShowAlertViewWithTitleString:#"ERROR":#"Problem in Network. Please Try Again!"];
[self.customerCareTableView setHidden:YES];
}
}
}
#catch (NSException *exception)
{
[self ShowAlertViewWithTitleString:#"":#"Problem In Network Connection. Please Try Again!"];
[self.customerCareTableView setHidden:YES];
}
#finally {
}
[self setShowingActivityIndicator:NO];
}
- (void)ShowAlertViewWithTitleString :(NSString *)title :(NSString *)message
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
I need to show a UIActivityIndicatorView when calling of a WebService is take place. However, the activity indicator keeps on showing even after i have received response from web service. It stops only after 5-6 seconds after i receive response. How to make it stop at the moment i am receiving a response?
Here's my code: (configuring UIActivityIndicatorView) and calling my webservice:
loadView = [[UIView alloc] initWithFrame:self.view.bounds];
loadView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
//UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] init];
//[second.loadingView addSubview:activityView];
//activityView.center = second.loadingView.center;
//[second.view addSubview:second.loadingView];
activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[loadView addSubview:activity];
activity.center = loadView.center;
[self.view addSubview:loadView];
[self.view bringSubviewToFront:loadView];
activity.hidesWhenStopped = YES;
[activity setHidden:NO];
//[activity performSelectorInBackground: #selector(startAnimating) withObject: nil];
[activity startAnimating];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self callRegisterWebService:self.userFname lastName:self.userLName email:self.userEmail];
});
I am stopping the animation in the finally block.
-(void)callRegisterWebService:(NSString *)fname lastName:(NSString *)lName email:(NSString *)email
{
NSString *serviceURL = [NSString stringWithFormat:#"https:abcdefghi..."];
#try {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
NSURLResponse *serviceResponse = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
if(!parsedData)
{
NSLog(#"data not parsed");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
else
{
NSString *status = [parsedData objectForKey:#"Status"];
if([status isEqualToString:#"Success"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NULL message:#"Authentication Token Has Been Sent To Your Email-ID!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
NSString *uniqueNumber = [parsedData objectForKey:#"UniqueNum"];
[self saveEmailAndUniqueNumberToDatabase:fname lastName:lName Email:email Number:uniqueNumber];
}
else if([status isEqualToString:#"Failed"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Not An Authorized User" message:#"Please Contact Admin To Get Access" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}
}
#catch (NSException *exception)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NULL message:#"Problem In Network Connection. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
#finally {
[activity stopAnimating];
[loadView setHidden:YES];
}
}
There are 2 issues in your code:
You are manipulating UI component from a background thread, never do that. Use main thread for UI manipulations
You wrote the activity indicator functionality in the finally clause, so it'll be hidden only after executing all the statements in try clause
Change your method like:
- (void) hideActivity
{
dispatch_async(dispatch_get_main_queue(), ^{
[activity stopAnimating];
[loadView setHidden:YES];
activity = nil;
loadView = nil;
});
}
-(void)callRegisterWebService:(NSString *)fname lastName:(NSString *)lName email:(NSString *)email
{
NSString *serviceURL = [NSString stringWithFormat:#"https:abcdefghi..."];
NSString *message = #"";
NSString *title = #"";
#try
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
NSURLResponse *serviceResponse = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
[self hideActivity];
if(!parsedData)
{
message = #"Problem in Network. Please Try Again!";
title = #"ERROR";
}
else
{
NSString *status = [parsedData objectForKey:#"Status"];
if([status isEqualToString:#"Success"])
{
message = #"Authentication Token Has Been Sent To Your Email-ID!";
title = nil;
NSString *uniqueNumber = [parsedData objectForKey:#"UniqueNum"];
[self saveEmailAndUniqueNumberToDatabase:fname lastName:lName Email:email Number:uniqueNumber];
}
else if([status isEqualToString:#"Failed"])
{
message = #"Please Contact Admin To Get Access";
title = #"Not An Authorized User";
}
else
{
message = #"Problem in Network. Please Try Again!";
title = #"ERROR";
}
}
}
#catch (NSException *exception)
{
if (activity != nil && loadView != nil)
{
[self hideActivity];
}
message = #"Problem In Network Connection. Please Try Again!";
title = nil;
}
#finally
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}