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.
Related
hi i am giving reference link of stack over flow
How to update Google Maps marker position in swift/iOS
You can try the online swift to objective c converters. Like
http://objc2swift.me
These converts are used to convert objective c to Swift. I know you want to convert Swift to objective C. But I think you can learn some think to here. Just write the code. Swift is very similar to objective c.Only difference in syntax. You can understand very easily.
*Stack Overflow not for Writing Codes. If you have any Problem in codes. We will help you.
Here is the code, Create a button, add selector to that button. Hope you will set your google map.
NSMutableData *webData;
#property NSURLConnection *connection;
-(void) getResult //call this in button selector
{
marker=nil; //create a GMSMarker globally.
[self.mapView clear];
NSString *strUrl = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%#&type=atm&sensor=true&name=%#&key=%#",latitude,longitude,_radius.text,_searchTxt.text,googleAPI_Key ];
[self addMarkerDataUrl:strUrl];
}
-(void)addMarkerDataUrl:(NSString *)urlString
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString* urlTextEscaped = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlTextEscaped]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
[request setHTTPMethod: #"GET"];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
if(self.connection)
{
webData = [[NSMutableData alloc]init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (webData)
{
[self gettingData:webData ];
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
webData=nil;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#" response %d",kCFURLErrorNotConnectedToInternet);
if ([error code] == kCFURLErrorNotConnectedToInternet)
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:#"No Connection Error"
forKey:NSLocalizedDescriptionKey];
NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:userInfo];
NSLog(#"error %#",noConnectionError);
[self handleError:noConnectionError];
}
else
{
[self handleError:error];
}
self.connection = nil;
[self errorInConnection];
}
- (void)handleError:(NSError *)error
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"SUBCOMMUNE" message:#"Timed Out" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
-(void)errorInConnection
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Try again after some time" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
- (void) gettingData:(NSData *)data
{
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray* places = [json objectForKey:#"results"];
NSLog(#"Google Data: %#", places);
tempArray = [[NSMutableArray alloc]init];
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if([[NSString stringWithFormat:#"%#",[allDataDictionary objectForKey:#"status"]]isEqualToString:#"OK"])
{
collectionArray =[[NSMutableArray alloc]init];
locArray = [[NSMutableArray alloc]init];
NSMutableArray *legsArray = [[NSMutableArray alloc] initWithArray:allDataDictionary[#"results"]];
for (int i=0; i< [legsArray count]; i++)
{
[collectionArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:legsArray[i][#"icon"],#"icon", legsArray[i][#"name"],#"name",legsArray [i][#"vicinity"],#"vicinity",legsArray[i][#"id"],#"id",nil]];
[locArray addObject:legsArray[i][#"geometry"][#"location"]];
[tempArray addObject:legsArray[i][#"vicinity"]];
}
NSLog(#"CollectionArray =%#",collectionArray);
NSLog(#"LocationArray =%lu",(unsigned long)locArray.count);
[self addMarkers];
}
else
{
NSString *msg=[allDataDictionary objectForKey:#"error_message"];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Error !\n Check Radius or ATM Name" message:msg delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
-(void)addMarkers
{
for(int i=0;i<locArray.count;i++)
{
starting = [NSMutableDictionary dictionaryWithObjectsAndKeys:locArray[i][#"lat"],#"lat",locArray[i][#"lng"],#"lng", nil];
name = [NSMutableDictionary dictionaryWithObjectsAndKeys:collectionArray[i][#"name"],#"name",nil];
CLLocationCoordinate2D position = CLLocationCoordinate2DMake([[starting objectForKey:#"lat"] doubleValue] , [[starting objectForKey:#"lng"] doubleValue]);
marker1 = [GMSMarker markerWithPosition:position];
GMSCameraUpdate *updatedCamera=[GMSCameraUpdate setTarget:CLLocationCoordinate2DMake(latitude, longitude) zoom:15];
[self.mapView animateWithCameraUpdate:updatedCamera];
marker1.title = [name objectForKey:#"name"];
[marker1 setIcon:[UIImage imageNamed:#"Map Pin-48.png"]];
marker1.appearAnimation = YES;
marker1.map = self.mapView;
}
}
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.
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!
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 have a progress bar in my app showing a percent value.
progressView = [[DDProgressView alloc] initWithFrame:CGRectMake(20.0f, 140.0f, self.view.bounds.size.width - 40.0f, 0.0f)];
[progressView setOuterColor:[UIColor grayColor]];
[progressView setInnerColor:[UIColor lightGrayColor]];
[self.view addSubview:progressView];
[progressView release];
float randomPercentageFloat = 40;
progressView.progress = randomPercentageFloat / 100;
This shows a progress bar which is 40% full. I want to make the progress bar to show a value from a php. I have a php file that echoes a value. I want to change the randomPercentageFloat = 40; to something like
float randomPercentageFloat = "www.website.com/value.php";
Is this possible? How can it be done?
You have to establish connection with your server e retrieve the value, following the sample cose
test.php contains this instruction:
<?php echo 40; ?>
here sample viewController.m with progress view linked via Interface Builder
#import "ViewController.h"
#interface ViewController () {
IBOutlet UIProgressView *progressView;
NSMutableData *receivedData;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
progressView.progressTintColor = [UIColor lightGrayColor];
progressView.trackTintColor = [UIColor grayColor];
progressView.progress = 0.0f;
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.0.29/test.php"]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (!theConnection) {
UIAlertView *connectFailMessage = [[UIAlertView alloc] initWithTitle:#"NSURLConnection " message:#"Failed in viewDidLoad" delegate: self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[connectFailMessage show];
}
}
#pragma mark NSURLConnection Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
receivedData = [NSMutableData data];
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// inform the user
UIAlertView *didFailWithErrorMessage = [[UIAlertView alloc] initWithTitle: #"NSURLConnection " message: #"didFailWithError" delegate: self cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[didFailWithErrorMessage show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *dataString = [[NSString alloc] initWithData: receivedData encoding:NSUTF8StringEncoding];
progressView.progress = [dataString floatValue] / 100;
}
#end