iOS Multiple UIpickerView not showing Arrays - ios

I have a hidden UIpickerView that should display a different Array depending on what button is pushed. The picker view shows up when the button is pushed but for some reason it doesn't show the Arrays in the picker view. I would be extremely grateful of any help!!!!
Here is the .m file:
#import "ViewController.h"
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>
#define GeoLocation TRUE // FALSE for no latitude/longitude information
#define kPICKERCOLUMN 1
typedef NS_ENUM(NSInteger, PickerType) {
CATEGORY_PICKER,
LOCATION_PICKER,
ORIGINATOR_PICKER,
DESTINATION_PICKER,
STATUS_PICKER
};
#define kPICKERCOLUMN 1
#define kPICKER_TAG 101
#interface ViewController ()
#end
#implementation ViewController
{
UIPickerView *picker;
PickerType pickerType;
}
#synthesize nameTextField, emailTextField, dateTextField, timeTextField, blankTextField, blankbTextField, mlabelcategory, messageTextView, categoryTypeBtn;
#synthesize name, emailaddress, date, time, blank, blankb, category, message, email, button;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
categoryTypes = [[NSArray alloc] initWithObjects:#"Appetizers",#"Breakfast",#"Dessert",#"Drinks",
#"Main Dish/Entree", #"Salad", #"Side Dish", #"Soup", #"Snack",
#"Baby Food", #"Pet Food",nil];
locationTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue"
,nil];
originatorTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
nil];
destinationTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
nil];
statusTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
nil];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
nameTextField.text = nil;
emailTextField.text = nil;
dateTextField.text = nil;
timeTextField.text = nil;
blankTextField.text = nil;
blankbTextField.text = nil;
mlabelcategory.text = nil;
messageTextView.text = nil;
picker = [[UIPickerView alloc] initWithFrame:CGRectMake(100,100,400,160)];
picker.showsSelectionIndicator = TRUE;
picker.dataSource = self;
picker.delegate = self;
picker.hidden = YES;
[self.view addSubview:picker];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)eve
{
picker.hidden = YES;
}
#pragma mark -
#pragma mark picker methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return kPICKERCOLUMN;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
switch (pickerType) {
case CATEGORY_PICKER:
return [categoryTypes count];;
break;
case LOCATION_PICKER:
return [locationTypes count];
break;
case ORIGINATOR_PICKER:
return [originatorTypes count];
break;
case DESTINATION_PICKER:
return [destinationTypes count];
break;
case STATUS_PICKER:
return [statusTypes count];
break;
default: return -1;
break;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
switch (pickerType) {
case CATEGORY_PICKER:
return [categoryTypes objectAtIndex:row];
break;
case LOCATION_PICKER:
return [locationTypes objectAtIndex:row];
break;
case ORIGINATOR_PICKER:
return [originatorTypes objectAtIndex:row];
break;
case DESTINATION_PICKER:
return [destinationTypes objectAtIndex:row];
break;
case STATUS_PICKER:
return [statusTypes objectAtIndex:row];
break;
default: return nil;
break;
}
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
switch (pickerType) {
case CATEGORY_PICKER: {
NSString *categoryType = [categoryTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[categoryTypeBtn setTitle:categoryType forState:UIControlStateNormal];
break;
}
case LOCATION_PICKER: {
NSString *locationType = [locationTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[locationTypeBtn setTitle:locationType forState:UIControlStateNormal];
break;
}
case ORIGINATOR_PICKER: {
NSString *originatorType = [originatorTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[originatorTypeBtn setTitle:originatorType forState:UIControlStateNormal];
break;
}
case DESTINATION_PICKER: {
NSString *destinationType = [destinationTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[destinationTypeBtn setTitle:destinationType forState:UIControlStateNormal];
break;
}
case STATUS_PICKER:{
NSString *statusType = [statusTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[statusTypeBtn setTitle:statusType forState:UIControlStateNormal];
break;
}
default:
break;
}
}
-(IBAction) showLocationTypePicker{
pickerType = LOCATION_PICKER;
picker.hidden = NO;
[picker reloadAllComponents];
}
-(IBAction) showCategoryTypePicker{
pickerType = CATEGORY_PICKER;
picker.hidden = NO;
[picker reloadAllComponents];
}
-(IBAction) showOriginatorTypePicker{
pickerType = ORIGINATOR_PICKER;
picker.hidden = NO;
[picker reloadAllComponents];
}
-(IBAction) showDestinationTypePicker{
pickerType = DESTINATION_PICKER;
picker.hidden = NO;
[picker reloadAllComponents];
}
-(IBAction) showStatusTypePicker{
pickerType = STATUS_PICKER;
picker.hidden = NO;
[picker reloadAllComponents];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
#pragma - getting info from the UI
//NSString *test = nil;
- (IBAction)checkData:(id)sender
{
/*
name = nameTextField.text;
surname = surnameTextField.text;
bornDate = bornDateTextField.text;
address = addressTextField.text;
zipCode = zipTextField.text;
email = emailTextField.text;
*/
//NSLog(#" Name: %# \n Surname: %# \n Date of Birth: %# \n Address: %# \n Post Code: %# \n email: %# \n", name, surname, bornDate, address, zipCode, email);
unsigned int x,a = 0;
NSMutableString *emailmessage; //stringa variabile
emailmessage = [NSMutableString stringWithFormat: #""]; //le stringhe mutabili vanno inizializzate in questo modo!
for (x=0; x<7; x++)
{
switch (x) {
case 0:
if (nameTextField.text == nil) {
[emailmessage appendString:#"Name, "];
a=1;
}
break;
case 1:
if (emailTextField.text == nil)
{
[emailmessage appendString:#"Email Address, "];
a=1;
}
break;
case 2:
if (dateTextField.text == nil)
{
[emailmessage appendString:#"Date of Near Miss, "];
a=1;
}
break;
case 3:
if (timeTextField.text == nil)
{
[emailmessage appendString:#"Time of Near Miss, "];
a=1;
}
break;
case 4:
if (blankTextField.text == nil)
{
[emailmessage appendString:#"Post Code, "];
a=1;
}
break;
case 5:
if (blankbTextField.text == nil)
{
[emailmessage appendString:#"Email, "];
a=1;
}
break;
case 6:
if (mlabelcategory.text == nil)
{
[emailmessage appendString:#"Category, "];
a=1;
}
break;
case 7:
if (messageTextView.text == nil)
{
[emailmessage appendString:#"Observation Description, "];
a=1;
}
break;
default:
break;
}
}
NSLog (#"Email Message: %#", emailmessage);
if (a == 1) {
NSMutableString *popupError;
popupError = [NSMutableString stringWithFormat: #"Per inviare compilare i seguenti campi: "];
[popupError appendString:emailmessage]; //aggiungo i miei errori
[popupError appendString: #" grazie della comprensione."]; //
NSLog(#"%#", popupError);
UIAlertView *chiamataEffettuata = [[UIAlertView alloc]
initWithTitle:#"ATTENTION" //titolo del mio foglio
message:popupError
delegate:self
cancelButtonTitle:#"Ok, correggo" //bottone con cui si chiude il messaggio
otherButtonTitles:nil, nil];
[chiamataEffettuata show]; //istanza per mostrare effettivamente il messaggio
}
else
{
name = nameTextField.text;
emailaddress = emailTextField.text;
date = dateTextField.text;
time = timeTextField.text;
blank = blankTextField.text;
blankb = blankbTextField.text;
category = mlabelcategory.text;
message = messageTextView.text;
NSMutableString *nearmissreport;
nearmissreport = [NSMutableString stringWithFormat: #"<br><br> <b>Name:</b> %# <br> <b>Email Address:</b> %# <br> <b>Date of Near Miss:</b> %# <br> <b>Time of Near Miss:</b> %# <br> <b>Post Code:</b> %# <br> <b>Email Address:</b> %# <br> <b>Category:</b> %# <br><b>Observation Description:</b> %# <br>", name, emailaddress, date, time, blank, blankb, category, message];
NSLog(#"Near Miss Report: %#", nearmissreport);
NSMutableString *testoMail;
testoMail = [NSMutableString stringWithFormat: nearmissreport];
NSLog(#"%#", testoMail);
//MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject: name];
// Set up the recipients.
NSArray *toRecipients = [NSArray arrayWithObjects:#"paul.haddell#bbmmjv.com",nil];
//NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com",#"third#example.com", nil];
//NSArray *bccRecipients = [NSArray arrayWithObjects:#"four#example.com",nil];
[picker setToRecipients:toRecipients];
//[picker setCcRecipients:ccRecipients];
//[picker setBccRecipients:bccRecipients];
// Attach an image to the email.
//NSString *path = [[NSBundle mainBundle] pathForResource:#"ipodnano" ofType:#"png"];
//NSData *myData = [NSData dataWithContentsOfFile:path];
//[picker addAttachmentData:myData mimeType:#"image/png" fileName:#"ipodnano"];
// Fill out the email body text.
//NSMutableString *emailBody;
testoMail = [NSMutableString stringWithFormat: #"%#", testoMail];
[picker setMessageBody:testoMail isHTML:YES]; //HTML!!!!!!
// Present the mail composition interface.
[self presentViewController:picker animated:YES completion:nil];
}
}
// The mail compose view controller delegate method
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error
{
[self dismissModalViewControllerAnimated:YES];
}
#pragma mark - Mandare email
/*
- (void)sendMail:(NSMutableString*)testoMail{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Reclutamento pompieri"];
// Set up the recipients.
NSArray *toRecipients = [NSArray arrayWithObjects:#"reda.bousbah#gmail.com",nil];
//NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com",#"third#example.com", nil];
//NSArray *bccRecipients = [NSArray arrayWithObjects:#"four#example.com",nil];
[picker setToRecipients:toRecipients];
//[picker setCcRecipients:ccRecipients];
//[picker setBccRecipients:bccRecipients];
// Attach an image to the email.
//NSString *path = [[NSBundle mainBundle] pathForResource:#"ipodnano" ofType:#"png"];
//NSData *myData = [NSData dataWithContentsOfFile:path];
//[picker addAttachmentData:myData mimeType:#"image/png" fileName:#"ipodnano"];
// Fill out the email body text.
NSString *emailBody = #"It is raining in sunny California!";
[picker setMessageBody:emailBody isHTML:NO];
// Present the mail composition interface.
[self presentViewController:picker animated:YES completion:nil];
}
*/
#pragma mark - methods to control the keyboard
- (IBAction)backgroundTap:(id)sender //method for resign the keyboard when the background is tapped
{
[nameTextField resignFirstResponder];
[emailTextField resignFirstResponder];
[dateTextField resignFirstResponder];
[timeTextField resignFirstResponder];
[blankTextField resignFirstResponder];
[blankbTextField resignFirstResponder];
[mlabelcategory resignFirstResponder];
[messageTextView resignFirstResponder];
}
- (IBAction)doneButtonPressed:(id)sender
{
NSLog( #"done button pressed");
[sender resignFirstResponder];
}
#end
Many Thanks

Related

How to Populate an email recipient depending on which button is pressed?

I have an app that is for 3 different offices and I would like to be able to choose which office the resulting collated data will be sent to via an email. I would like to use a different button for each of the offices that will automatically populate an email recipient and then a final button at the end will collate all the information and attach it all to an email. Is there any way of doing this? I have the send button figured out, its the populating the recipient that I can't work out.
Here is the email part that I have but is populated by 1 email address rather than depending on a button press at the moment.
- (IBAction)checkData:(id)sender
{
unsigned int x,a = 0;
NSMutableString *emailmessage;
emailmessage = [NSMutableString stringWithFormat: #""];
for (x=0; x<9; x++)
{
switch (x) {
case 0:
if (nameTextField.text == nil) {
[emailmessage appendString:#"Name, "];
a=1;
}
break;
case 1:
if (emailTextField.text == nil)
{
[emailmessage appendString:#"Email Address, "];
a=1;
}
break;
case 2:
if (dateLabel.text == nil)
{
[emailmessage appendString:#"Date and Time of Near Miss, "];
a=1;
}
break;
case 3:
if (locationTextField.text == nil)
{
[emailmessage appendString:#"Location of Near Miss, "];
a=1;
}
break;
case 4:
if (locLabel.text == nil)
{
[emailmessage appendString:#"GPS Location, "];
a=1;
}
break;
case 5:
if (observersTextField.text == nil)
{
[emailmessage appendString:#"Observers Team, "];
a=1;
}
break;
case 6:
if (affectedTextField.text == nil)
{
[emailmessage appendString:#"Affected Team, "];
a=1;
}
break;
case 7:
if (catLabel.text == nil)
{
[emailmessage appendString:#"Rating Classification, "];
a=1;
}
break;
case 8:
if (onOffLabel.text == nil)
{
[emailmessage appendString:#"Third Party?, "];
a=1;
}
break;
case 9:
if (mlabelcategory.text == nil)
{
[emailmessage appendString:#"Category, "];
a=1;
}
break;
case 10:
if (messageTextView.text == nil)
{
[emailmessage appendString:#"Observation Description, "];
a=1;
}
break;
case 11:
if (activityTextView.text == nil)
{
[emailmessage appendString:#"Type of Work Activity, "];
a=1;
}
break;
case 12:
if (imageView.image == nil)
{
[emailmessage appendString:#"Image, "];
a=1;
}
break;
default:
break;
}
}
{
name = nameTextField.text;
emailaddress = emailTextField.text;
date = dateLabel.text;
location = locationTypeBtn.text;
observers = originatorTypeBtn.text;
affected = destinationTypeBtn.text;
rating = catLabel.text;
thirdparty = onOffLabel.text;
category = categoryTypeBtn.text;
message = messageTextView.text;
activity = activityTextView.text;
gps = locLabel.text;
NSMutableString *nearmissreport;
nearmissreport = [NSMutableString stringWithFormat: #"<br><br> <b>Name:</b> %# <br> <b>Email Address:</b> %# <br><br> <b>Date & Time of Near Miss:</b> %# <br><br> <b>Location of Near Miss:</b> %# <br> <b>GPS Location:</b> %# <br><br> <b>Observers Team:</b> %# <br> <b>Affected Team:</b> %# <br><br> <b>Rating Classification:</b> %# <br><br> %# <br><br> <b>Category:</b> %# <br><b>Observation Description:</b> %# <br><br> <b>Type of Work Activity:</b> %# <br><br><b>Image:</b><br>", name, emailaddress, date, location, gps, observers, affected, rating, thirdparty, category, message, activity];
NSLog(#"Near Miss Report: %#", nearmissreport);
NSMutableString *testoMail;
testoMail = [NSMutableString stringWithFormat: nearmissreport];
NSLog(#"%#", testoMail);
//MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject: rating];
// Set up the recipients.
NSArray *toRecipients = [NSArray arrayWithObjects:#"example#example.com",nil];
//NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com",#"third#example.com", nil];
//NSArray *bccRecipients = [NSArray arrayWithObjects:#"four#example.com",nil];
[picker setToRecipients:toRecipients];
//[picker setCcRecipients:ccRecipients];
//[picker setBccRecipients:bccRecipients];
// Attach an image to the email.
NSData *imageData = UIImagePNGRepresentation([imageView image]);
[picker addAttachmentData:imageData mimeType:#"image/png" fileName:#"NearMiss"];
// Fill out the email body text.
//NSMutableString *emailBody;
testoMail = [NSMutableString stringWithFormat: #"%#", testoMail];
[picker setMessageBody:testoMail isHTML:YES]; //HTML!!!!!!
// Present the mail composition interface.
[self presentViewController:picker animated:YES completion:nil];
}
}
// The mail compose view controller delegate method
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error
{
[self dismissModalViewControllerAnimated:YES];
}
Why not implement the method that's called when your button is pressed, parse out the id of the button from the info that was passed in, and then set the "to" field of the email accordingly?
-(IBAction)buttonPressed:(id)sender{
UIButton *button = (UIButton *)sender;
NSLog(#"%d", [button tag]);
switch(button.tag) {
case 1 :
// set label.text = example1#example.com
break;
case 2 :
// set label.text = example2#example.com
break;
}
}
Try this
- (IBAction)sendEmail:(id)sender {
NSMutableString *report = [NSMutableString stringWithFormat: #"<br><br> <b>Name:</b> %# <br> <b>Email Address:</b> %# <br><br> <b>Date & Time of Near Miss:</b> %# <br><br> <b>Location of Near Miss:</b> %# <br> <b>GPS Location:</b> %# <br><br> <b>Observers Team:</b> %# <br> <b>Affected Team:</b> %# <br><br> <b>Rating Classification:</b> %# <br><br> %# <br><br> <b>Category:</b> %# <br><b>Observation Description:</b> %# <br><br> <b>Type of Work Activity:</b> %# <br><br><b>Image:</b><br>", name, emailaddress, date, location, gps, observers, affected, rating, thirdparty, category, message, activity];
NSLog(#"Near Miss Report: %#", report);
NSMutableString *testoMail = [NSMutableString stringWithFormat:report];
NSLog(#"%#", testoMail);
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject: rating];
// Set up the recipients.
NSArray *toRecipients;
NSArray *ccRecipients;
NSArray *bccRecipients;
switch([sender tag]) {
case 0 : {
// set label.text = example1#example.com
toRecipients = [NSArray arrayWithObjects:#"example#example.com",nil];
ccRecipients = [NSArray arrayWithObjects:#"second#example.com",#"third#example.com", nil];
bccRecipients = [NSArray arrayWithObjects:#"four#example.com",nil];
break;
}
case 1 : {
// set label.text = example2#example.com
toRecipients = [NSArray arrayWithObjects:#"example#example.com",nil];
ccRecipients = [NSArray arrayWithObjects:#"second#example.com",#"third#example.com", nil];
bccRecipients = [NSArray arrayWithObjects:#"four#example.com",nil];
break;
}
case 2 : {
// set label.text = example2#example.com
toRecipients = [NSArray arrayWithObjects:#"example#example.com",nil];
ccRecipients = [NSArray arrayWithObjects:#"second#example.com",#"third#example.com", nil];
bccRecipients = [NSArray arrayWithObjects:#"four#example.com",nil];
break;
}
}
if(toRecipients.length >0) {
[picker setToRecipients:toRecipients];
}
if(ccRecipients.length >0) {
[picker setCcRecipients:ccRecipients];
}
if(bccRecipients.length >0) {
[picker setBccRecipients:bccRecipients];
}
// Attach an image to the email.
NSData *imageData = UIImagePNGRepresentation([imageView image]);
[picker addAttachmentData:imageData mimeType:#"image/png" fileName:#"NearMiss"];
// Fill out the email body text.
//NSMutableString *emailBody;
testoMail = [NSMutableString stringWithFormat: #"%#", testoMail];
[picker setMessageBody:testoMail isHTML:YES]; //HTML!!!!!!
// Present the mail composition interface.
[self presentViewController:picker animated:YES completion:nil];
}

iOS "Control may reach end of non-void function"

Any idea why I am getting 2 errors of the below code of "Control may reach end of non-void function"? I had it working in a separate app but for some reason coming up with this error now.
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
switch (pickerView.tag) {
case kCATEGORYTYPEPICKERTAG:
return [categoryTypes count];;
break;
case kLOCATIONTYPEPICKERTAG:
return [locationTypes count];
break;
case kORIGINATORTYPEPICKERTAG:
return [originatorTypes count];
break;
case kDESTINATIONTYPEPICKERTAG:
return [destinationTypes count];
break;
case kSTATUSTYPEPICKERTAG:
return [statusTypes count];
break;
default:
break;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
switch (pickerView.tag) {
case kCATEGORYTYPEPICKERTAG:
return [categoryTypes objectAtIndex:row];
break;
case kLOCATIONTYPEPICKERTAG:
return [locationTypes objectAtIndex:row];
break;
case kORIGINATORTYPEPICKERTAG:
return [originatorTypes objectAtIndex:row];
break;
case kDESTINATIONTYPEPICKERTAG:
return [destinationTypes objectAtIndex:row];
break;
case kSTATUSTYPEPICKERTAG:
return [statusTypes objectAtIndex:row];
break;
default:
break;
}
}
Many Thanks
UPDATE
Full code:
#synthesize nameTextField, emailTextField, dateTextField, timeTextField, blankTextField, blankbTextField, mlabelcategory, messageTextView;
#synthesize name, emailaddress, date, time, blank, blankb, category, message;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
categoryTypes = [[NSArray alloc] initWithObjects:#"Appetizers",#"Breakfast",#"Dessert",#"Drinks",
#"Main Dish/Entree", #"Salad", #"Side Dish", #"Soup", #"Snack",
#"Baby Food", #"Pet Food",nil];
locationTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
#"Brazilian", #"British", #"Cajun", #"Central American", #"Chicken",
#"Chinese", #"Cuban",
#"Ethiopian", #"French", #"Greek", #"German", #"Hamburgers",
#"Homestyle Cooking", #"Indian", #"Irish", #"Italian", #"Jamaican",
#"Japanese", #"Korean", #"Mexican", #"Middle Eastern", #"Pakistani",
#"Pancakes /Waffles", #"Persian", #"Pizza", #"Polynesian", #"Russian",
#"Sandwiches", #"Seafood", #"Scandinavian", #"Spanish", #"Soul Food",
#"South American", #"Steak", #"Vegetarian", #"Tex-Mex", #"Thai",
#"Vietnamese",#"Wild Game",nil];
originatorTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
#"Brazilian", #"British", #"Cajun", #"Central American", #"Chicken",
#"Chinese", #"Cuban",
#"Ethiopian", #"French", #"Greek", #"German", #"Hamburgers",
#"Homestyle Cooking", #"Indian", #"Irish", #"Italian", #"Jamaican",
#"Japanese", #"Korean", #"Mexican", #"Middle Eastern", #"Pakistani",
#"Pancakes /Waffles", #"Persian", #"Pizza", #"Polynesian", #"Russian",
#"Sandwiches", #"Seafood", #"Scandinavian", #"Spanish", #"Soul Food",
#"South American", #"Steak", #"Vegetarian", #"Tex-Mex", #"Thai",
#"Vietnamese",#"Wild Game",nil];
destinationTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
#"Brazilian", #"British", #"Cajun", #"Central American", #"Chicken",
#"Chinese", #"Cuban",
#"Ethiopian", #"French", #"Greek", #"German", #"Hamburgers",
#"Homestyle Cooking", #"Indian", #"Irish", #"Italian", #"Jamaican",
#"Japanese", #"Korean", #"Mexican", #"Middle Eastern", #"Pakistani",
#"Pancakes /Waffles", #"Persian", #"Pizza", #"Polynesian", #"Russian",
#"Sandwiches", #"Seafood", #"Scandinavian", #"Spanish", #"Soul Food",
#"South American", #"Steak", #"Vegetarian", #"Tex-Mex", #"Thai",
#"Vietnamese",#"Wild Game",nil];
statusTypes = [[NSArray alloc] initWithObjects:#"African",#"American",#"Armenian",#"Barbecue",
#"Brazilian", #"British", #"Cajun", #"Central American", #"Chicken",
#"Chinese", #"Cuban",
#"Ethiopian", #"French", #"Greek", #"German", #"Hamburgers",
#"Homestyle Cooking", #"Indian", #"Irish", #"Italian", #"Jamaican",
#"Japanese", #"Korean", #"Mexican", #"Middle Eastern", #"Pakistani",
#"Pancakes /Waffles", #"Persian", #"Pizza", #"Polynesian", #"Russian",
#"Sandwiches", #"Seafood", #"Scandinavian", #"Spanish", #"Soul Food",
#"South American", #"Steak", #"Vegetarian", #"Tex-Mex", #"Thai",
#"Vietnamese",#"Wild Game",nil];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
nameTextField.text = nil;
emailTextField.text = nil;
dateTextField.text = nil;
timeTextField.text = nil;
blankTextField.text = nil;
blankbTextField.text = nil;
mlabelcategory.text = nil;
messageTextView.text = nil;
categoryTypePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(300,400,400,160)];
categoryTypePicker.tag = kCATEGORYTYPEPICKERTAG;
categoryTypePicker.showsSelectionIndicator = TRUE;
categoryTypePicker.dataSource = self;
categoryTypePicker.delegate = self;
categoryTypePicker.hidden = YES;
locationTypePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0,250,400,160)];
locationTypePicker.backgroundColor = [UIColor blueColor];
locationTypePicker.tag = kLOCATIONTYPEPICKERTAG;
locationTypePicker.showsSelectionIndicator = TRUE;
locationTypePicker.hidden = YES;
locationTypePicker.dataSource = self;
locationTypePicker.delegate = self;
originatorTypePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0,250,400,160)];
originatorTypePicker.backgroundColor = [UIColor blueColor];
originatorTypePicker.tag = kORIGINATORTYPEPICKERTAG;
originatorTypePicker.showsSelectionIndicator = TRUE;
originatorTypePicker.hidden = YES;
originatorTypePicker.dataSource = self;
originatorTypePicker.delegate = self;
destinationTypePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0,250,400,160)];
destinationTypePicker.backgroundColor = [UIColor blueColor];
destinationTypePicker.tag = kDESTINATIONTYPEPICKERTAG;
destinationTypePicker.showsSelectionIndicator = TRUE;
destinationTypePicker.hidden = YES;
destinationTypePicker.dataSource = self;
destinationTypePicker.delegate = self;
statusTypePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0,250,400,160)];
statusTypePicker.backgroundColor = [UIColor blueColor];
statusTypePicker.tag = kSTATUSTYPEPICKERTAG;
statusTypePicker.showsSelectionIndicator = TRUE;
statusTypePicker.hidden = YES;
statusTypePicker.dataSource = self;
statusTypePicker.delegate = self;
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)eve
{
if ( !locationTypePicker.hidden) {
locationTypePicker.hidden = YES;
}
if ( !categoryTypePicker.hidden) {
categoryTypePicker.hidden = YES;
}
if ( !originatorTypePicker.hidden) {
originatorTypePicker.hidden = YES;
}
if ( !destinationTypePicker.hidden) {
destinationTypePicker.hidden = YES;
}
if ( !statusTypePicker.hidden) {
statusTypePicker.hidden = YES;
}
}
#pragma mark -
#pragma mark picker methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return kPICKERCOLUMN;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
switch (pickerView.tag) {
case kCATEGORYTYPEPICKERTAG:
return [categoryTypes count];;
break;
case kLOCATIONTYPEPICKERTAG:
return [locationTypes count];
break;
case kORIGINATORTYPEPICKERTAG:
return [originatorTypes count];
break;
case kDESTINATIONTYPEPICKERTAG:
return [destinationTypes count];
break;
case kSTATUSTYPEPICKERTAG:
return [statusTypes count];
break;
default: return nil; break;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
switch (pickerView.tag) {
case kCATEGORYTYPEPICKERTAG:
return [categoryTypes objectAtIndex:row];
break;
case kLOCATIONTYPEPICKERTAG:
return [locationTypes objectAtIndex:row];
break;
case kORIGINATORTYPEPICKERTAG:
return [originatorTypes objectAtIndex:row];
break;
case kDESTINATIONTYPEPICKERTAG:
return [destinationTypes objectAtIndex:row];
break;
case kSTATUSTYPEPICKERTAG:
return [statusTypes objectAtIndex:row];
break;
default: return nil; break;
}
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (pickerView.tag == kCATEGORYTYPEPICKERTAG) {
NSString *categoryType = [categoryTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[categoryTypeBtn setTitle:categoryType forState:UIControlStateNormal];
}else if (pickerView.tag == kLOCATIONTYPEPICKERTAG) {
NSString *locationType = [locationTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[locationTypeBtn setTitle:locationType forState:UIControlStateNormal];
}else if (pickerView.tag == kORIGINATORTYPEPICKERTAG) {
NSString *originatorType = [originatorTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[originatorTypeBtn setTitle:originatorType forState:UIControlStateNormal];
}else if (pickerView.tag == kDESTINATIONTYPEPICKERTAG) {
NSString *destinationType = [destinationTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[destinationTypeBtn setTitle:destinationType forState:UIControlStateNormal];
}else if (pickerView.tag == kSTATUSTYPEPICKERTAG) {
NSString *statusType = [statusTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
[statusTypeBtn setTitle:statusType forState:UIControlStateNormal];
}
}
-(IBAction) showLocationTypePicker{
if ( locationTypePicker.hidden) {
locationTypePicker.hidden = NO;
[self.view addSubview:locationTypePicker];
}
else {
locationTypePicker.hidden = NO;
[locationTypePicker removeFromSuperview];
}
if ( categoryTypePicker.hidden) {
categoryTypePicker.hidden = YES;
[self.view addSubview:categoryTypePicker];
}
else {
categoryTypePicker.hidden = YES;
[categoryTypePicker removeFromSuperview];
}
if ( originatorTypePicker.hidden) {
originatorTypePicker.hidden = YES;
[self.view addSubview:originatorTypePicker];
}
else {
originatorTypePicker.hidden = YES;
[originatorTypePicker removeFromSuperview];
}
if ( destinationTypePicker.hidden) {
destinationTypePicker.hidden = YES;
[self.view addSubview:destinationTypePicker];
}
else {
destinationTypePicker.hidden = YES;
[destinationTypePicker removeFromSuperview];
}
if ( statusTypePicker.hidden) {
statusTypePicker.hidden = YES;
[self.view addSubview:statusTypePicker];
}
else {
statusTypePicker.hidden = YES;
[statusTypePicker removeFromSuperview];
}
}
-(IBAction) showCategoryTypePicker{
if ( categoryTypePicker.hidden) {
categoryTypePicker.hidden = NO;
[self.view addSubview:categoryTypePicker];
}
else {
categoryTypePicker.hidden = NO;
[categoryTypePicker removeFromSuperview];
}
if ( locationTypePicker.hidden) {
locationTypePicker.hidden = YES;
[self.view addSubview:locationTypePicker];
}
else {
locationTypePicker.hidden = YES;
[locationTypePicker removeFromSuperview];
}
if ( originatorTypePicker.hidden) {
originatorTypePicker.hidden = YES;
[self.view addSubview:originatorTypePicker];
}
else {
originatorTypePicker.hidden = YES;
[originatorTypePicker removeFromSuperview];
}
if ( destinationTypePicker.hidden) {
destinationTypePicker.hidden = YES;
[self.view addSubview:destinationTypePicker];
}
else {
destinationTypePicker.hidden = YES;
[destinationTypePicker removeFromSuperview];
}
if ( statusTypePicker.hidden) {
statusTypePicker.hidden = YES;
[self.view addSubview:statusTypePicker];
}
else {
statusTypePicker.hidden = YES;
[statusTypePicker removeFromSuperview];
}
}
-(IBAction) showOriginatorTypePicker{
if ( originatorTypePicker.hidden) {
originatorTypePicker.hidden = NO;
[self.view addSubview:originatorTypePicker];
}
else {
originatorTypePicker.hidden = NO;
[originatorTypePicker removeFromSuperview];
}
if ( locationTypePicker.hidden) {
locationTypePicker.hidden = YES;
[self.view addSubview:locationTypePicker];
}
else {
locationTypePicker.hidden = YES;
[locationTypePicker removeFromSuperview];
}
if ( categoryTypePicker.hidden) {
categoryTypePicker.hidden = YES;
[self.view addSubview:categoryTypePicker];
}
else {
categoryTypePicker.hidden = YES;
[categoryTypePicker removeFromSuperview];
}
if ( destinationTypePicker.hidden) {
destinationTypePicker.hidden = YES;
[self.view addSubview:destinationTypePicker];
}
else {
destinationTypePicker.hidden = YES;
[destinationTypePicker removeFromSuperview];
}
if ( statusTypePicker.hidden) {
statusTypePicker.hidden = YES;
[self.view addSubview:statusTypePicker];
}
else {
statusTypePicker.hidden = YES;
[statusTypePicker removeFromSuperview];
}
}
-(IBAction) showDestinationTypePicker{
if ( destinationTypePicker.hidden) {
destinationTypePicker.hidden = NO;
[self.view addSubview:destinationTypePicker];
}
else {
destinationTypePicker.hidden = NO;
[destinationTypePicker removeFromSuperview];
}
if ( locationTypePicker.hidden) {
locationTypePicker.hidden = YES;
[self.view addSubview:locationTypePicker];
}
else {
locationTypePicker.hidden = YES;
[locationTypePicker removeFromSuperview];
}
if ( originatorTypePicker.hidden) {
originatorTypePicker.hidden = YES;
[self.view addSubview:originatorTypePicker];
}
else {
originatorTypePicker.hidden = YES;
[originatorTypePicker removeFromSuperview];
}
if ( categoryTypePicker.hidden) {
categoryTypePicker.hidden = YES;
[self.view addSubview:categoryTypePicker];
}
else {
categoryTypePicker.hidden = YES;
[categoryTypePicker removeFromSuperview];
}
if ( statusTypePicker.hidden) {
statusTypePicker.hidden = YES;
[self.view addSubview:statusTypePicker];
}
else {
statusTypePicker.hidden = YES;
[statusTypePicker removeFromSuperview];
}
}
-(IBAction) showStatusTypePicker{
if ( statusTypePicker.hidden) {
statusTypePicker.hidden = NO;
[self.view addSubview:statusTypePicker];
}
else {
statusTypePicker.hidden = NO;
[statusTypePicker removeFromSuperview];
}
if ( locationTypePicker.hidden) {
locationTypePicker.hidden = YES;
[self.view addSubview:locationTypePicker];
}
else {
locationTypePicker.hidden = YES;
[locationTypePicker removeFromSuperview];
}
if ( originatorTypePicker.hidden) {
originatorTypePicker.hidden = YES;
[self.view addSubview:originatorTypePicker];
}
else {
originatorTypePicker.hidden = YES;
[originatorTypePicker removeFromSuperview];
}
if ( destinationTypePicker.hidden) {
destinationTypePicker.hidden = YES;
[self.view addSubview:destinationTypePicker];
}
else {
destinationTypePicker.hidden = YES;
[destinationTypePicker removeFromSuperview];
}
if ( categoryTypePicker.hidden) {
categoryTypePicker.hidden = YES;
[self.view addSubview:categoryTypePicker];
}
else {
categoryTypePicker.hidden = YES;
[categoryTypePicker removeFromSuperview];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
#pragma - getting info from the UI
//NSString *test = nil;
- (IBAction)checkData:(id)sender
{
/*
name = nameTextField.text;
surname = surnameTextField.text;
bornDate = bornDateTextField.text;
address = addressTextField.text;
zipCode = zipTextField.text;
email = emailTextField.text;
*/
//NSLog(#" Name: %# \n Surname: %# \n Date of Birth: %# \n Address: %# \n Post Code: %# \n email: %# \n", name, surname, bornDate, address, zipCode, email);
unsigned int x,a = 0;
NSMutableString *emailmessage; //stringa variabile
emailmessage = [NSMutableString stringWithFormat: #""]; //le stringhe mutabili vanno inizializzate in questo modo!
for (x=0; x<7; x++)
{
switch (x) {
case 0:
if (nameTextField.text == nil) {
[emailmessage appendString:#"Name, "];
a=1;
}
break;
case 1:
if (emailTextField.text == nil)
{
[emailmessage appendString:#"Email Address, "];
a=1;
}
break;
case 2:
if (dateTextField.text == nil)
{
[emailmessage appendString:#"Date of Near Miss, "];
a=1;
}
break;
case 3:
if (timeTextField.text == nil)
{
[emailmessage appendString:#"Time of Near Miss, "];
a=1;
}
break;
case 4:
if (blankTextField.text == nil)
{
[emailmessage appendString:#"Post Code, "];
a=1;
}
break;
case 5:
if (blankbTextField.text == nil)
{
[emailmessage appendString:#"Email, "];
a=1;
}
break;
case 6:
if (mlabelcategory.text == nil)
{
[emailmessage appendString:#"Category, "];
a=1;
}
break;
case 7:
if (messageTextView.text == nil)
{
[emailmessage appendString:#"Observation Description, "];
a=1;
}
break;
default:
break;
}
}
NSLog (#"Email Message: %#", emailmessage);
if (a == 1) {
NSMutableString *popupError;
popupError = [NSMutableString stringWithFormat: #"Per inviare compilare i seguenti campi: "];
[popupError appendString:emailmessage]; //aggiungo i miei errori
[popupError appendString: #" grazie della comprensione."]; //
NSLog(#"%#", popupError);
UIAlertView *chiamataEffettuata = [[UIAlertView alloc]
initWithTitle:#"ATTENTION" //titolo del mio foglio
message:popupError
delegate:self
cancelButtonTitle:#"Ok, correggo" //bottone con cui si chiude il messaggio
otherButtonTitles:nil, nil];
[chiamataEffettuata show]; //istanza per mostrare effettivamente il messaggio
}
else
{
name = nameTextField.text;
emailaddress = emailTextField.text;
date = dateTextField.text;
time = timeTextField.text;
blank = blankTextField.text;
blankb = blankbTextField.text;
category = mlabelcategory.text;
message = messageTextView.text;
NSMutableString *nearmissreport;
nearmissreport = [NSMutableString stringWithFormat: #"<br><br> <b>Name:</b> %# <br> <b>Email Address:</b> %# <br> <b>Date of Near Miss:</b> %# <br> <b>Time of Near Miss:</b> %# <br> <b>Post Code:</b> %# <br> <b>Email Address:</b> %# <br> <b>Category:</b> %# <br><b>Observation Description:</b> %# <br>", name, emailaddress, date, time, blank, blankb, category, message];
NSLog(#"Near Miss Report: %#", nearmissreport);
NSMutableString *testoMail;
testoMail = [NSMutableString stringWithFormat: nearmissreport];
NSLog(#"%#", testoMail);
//MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject: name];
// Set up the recipients.
NSArray *toRecipients = [NSArray arrayWithObjects:#"paul.haddell#bbmmjv.com",nil];
//NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com",#"third#example.com", nil];
//NSArray *bccRecipients = [NSArray arrayWithObjects:#"four#example.com",nil];
[picker setToRecipients:toRecipients];
//[picker setCcRecipients:ccRecipients];
//[picker setBccRecipients:bccRecipients];
// Attach an image to the email.
//NSString *path = [[NSBundle mainBundle] pathForResource:#"ipodnano" ofType:#"png"];
//NSData *myData = [NSData dataWithContentsOfFile:path];
//[picker addAttachmentData:myData mimeType:#"image/png" fileName:#"ipodnano"];
// Fill out the email body text.
//NSMutableString *emailBody;
testoMail = [NSMutableString stringWithFormat: #"%#", testoMail];
[picker setMessageBody:testoMail isHTML:YES]; //HTML!!!!!!
// Present the mail composition interface.
[self presentViewController:picker animated:YES completion:nil];
}
}
// The mail compose view controller delegate method
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error
{
[self dismissModalViewControllerAnimated:YES];
}
#pragma mark - Mandare email
/*
- (void)sendMail:(NSMutableString*)testoMail{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Reclutamento pompieri"];
// Set up the recipients.
NSArray *toRecipients = [NSArray arrayWithObjects:#"reda.bousbah#gmail.com",nil];
//NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com",#"third#example.com", nil];
//NSArray *bccRecipients = [NSArray arrayWithObjects:#"four#example.com",nil];
[picker setToRecipients:toRecipients];
//[picker setCcRecipients:ccRecipients];
//[picker setBccRecipients:bccRecipients];
// Attach an image to the email.
//NSString *path = [[NSBundle mainBundle] pathForResource:#"ipodnano" ofType:#"png"];
//NSData *myData = [NSData dataWithContentsOfFile:path];
//[picker addAttachmentData:myData mimeType:#"image/png" fileName:#"ipodnano"];
// Fill out the email body text.
NSString *emailBody = #"It is raining in sunny California!";
[picker setMessageBody:emailBody isHTML:NO];
// Present the mail composition interface.
[self presentViewController:picker animated:YES completion:nil];
}
*/
#pragma mark - methods to control the keyboard
- (IBAction)backgroundTap:(id)sender //method for resign the keyboard when the background is tapped
{
[nameTextField resignFirstResponder];
[emailTextField resignFirstResponder];
[dateTextField resignFirstResponder];
[timeTextField resignFirstResponder];
[blankTextField resignFirstResponder];
[blankbTextField resignFirstResponder];
[mlabelcategory resignFirstResponder];
[messageTextView resignFirstResponder];
}
- (IBAction)doneButtonPressed:(id)sender
{
NSLog( #"done button pressed");
[sender resignFirstResponder];
}
This happens because in case you tag property doesn't fall into any of the cases, it goes to the default block which in turn won't return anything.
You need to return a default value (nil,0) in the default block:
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
NSInteger numberOfRows = 0;
switch (pickerView.tag) {
case kCATEGORYTYPEPICKERTAG: {
numberOfRows = [categoryTypes count];
break;
}
case kLOCATIONTYPEPICKERTAG: {
numberOfRows = [locationTypes count];
break;
}
case kORIGINATORTYPEPICKERTAG: {
numberOfRows = [originatorTypes count];
break;
}
case kDESTINATIONTYPEPICKERTAG: {
numberOfRows = [destinationTypes count];
break;
}
case kSTATUSTYPEPICKERTAG: {
numberOfRows = [statusTypes count];
break;
}
default: {
break;
}
}
return numberOfRows;
}
You'll also have to do this in the titleForRow method.
Also:
I prefer having minimal amount of returns and modifying a value
instead which I will return at the end
Enclosing cases in {}.

textFieldDidBeginEditing not fired at first tap

When i tap the textfield textFieldDidBeginEditing starts to be fired after second tap. When I remove below code and after inside the textFieldDidBeginEditing method. It is fired at first tap. How can I make it fired at first tap?
[numKeyboard.view setFrame:CGRectMake(0,
self.view.frame.size.height-numKeyboard.view.frame.size.height, 320,
320)];
.m file:
#import "MainViewController.h"
#import "HastaDAO.h"
#import "YatanHastaBilgileriDAO.h"
#import "SettingViewController.h"
#import "Global.h"
#import <AudioToolbox/AudioServices.h>
#import "AlerjiModel.h"
#import "AlerjiDAO.h"
#import "NumKeyboard.h"
#interface MainViewController ()
{
int whichbtn;
}
#end
#implementation MainViewController
#synthesize player=_player;
#synthesize resultText1, resultText2,result,closeResult;
NSMutableArray *favTani;
HastaModel *yatanHastaBilgisi;
NSString *currentKey,*sound;
NSString *currentStringValue;
HastaModel *hasta;
int compareResult;
NSString *string=#"";
NSInteger didCompare=1;
UIImage *img;
NSString *str1,*str2;
NSInteger fromHistory=0;
-(void)viewDidAppear:(BOOL)animated{
if(fromHistory){
self.resultText1.text=str1;
self.resultText2.text=str2;
}
}
+(void)set_from_view:(NSInteger)history scanner:(NSInteger)scanner{
fromHistory=history;
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
if (textField == self.resultText2 && (![self.resultText1.text isEqualToString:#""] && ![self.resultText2.text isEqualToString:#""])){
[self destroyNumKeyboard];
[self compareTwoBarcode];
}
}
+(void)setResultTexts:(NSString*)str img:(UIImage*)image{
string=str;
img=[[UIImage alloc]init];
img=image;
}
-(void)compareTwoBarcode{
[self.resultText1 resignFirstResponder];
[self.resultText2 resignFirstResponder];
if(![self.resultText1.text isEqualToString:#""] && ![self.resultText2.text isEqualToString:#""] )
{
didCompare=1;
if ([resultText1.text isEqualToString:resultText2.text]) {
sound=#"%#/accept.mp3";
result.text = #"EŞLEŞİYOR";
result.backgroundColor = [UIColor colorWithRed:153/255.0 green:255/255.0 blue:51/255.0 alpha:0.85];
compareResult=1;
}
else
{
sound=#"%#/reject.mp3";
result.text = #"EŞLEŞMİYOR";
result.backgroundColor = [UIColor colorWithRed:255/255.0 green:0/255.0 blue:0/255.0 alpha:0.85];
compareResult=0;
}
[closeResult setHidden:FALSE];
[result setHidden:FALSE];
NSString *soundFilePath = [NSString stringWithFormat:sound, [[NSBundle mainBundle] resourcePath]];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = 1; //Infinite
if([SettingViewController getVolume])
[player play];
if([SettingViewController getVibrate]){
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Uyarı"
message:#"Barkod alanları dolu olmalıdır!"
delegate:nil
cancelButtonTitle:#"Tamam"
otherButtonTitles:nil];
[alert show];
}
}
-(void)setHistorySource{
NSString *word= self.resultText1.text;
NSString *pathhistory = [[self documentsDirectory] stringByAppendingPathComponent:#"history.plist"];
NSMutableArray *histList = [[NSMutableArray alloc] initWithContentsOfFile:pathhistory];
NSInteger ishist=0;
for (NSInteger i=[histList count]-1; i>=0;i--) {
NSDictionary *d = [histList objectAtIndex:i];
//NSString *patientName=[d objectForKey:#"PATIENT"];
NSString *name1=[d objectForKey:#"WORD1"];
NSString *name2=[d objectForKey:#"WORD2"];
if([name1 isEqualToString:self.resultText1.text] &&
[name2 isEqualToString:self.resultText2.text])
ishist=1;
}
if(ishist==0){
HastaModel*hmodel=[[HastaModel alloc]init];
NSMutableArray *arr=[HastaDAO getHasta:[self.resultText1.text intValue] yatanAyaktan:1];
if([arr count]==0)
arr=[HastaDAO getHasta:[self.resultText1.text intValue] yatanAyaktan:0];
if([arr count]){
hmodel=[arr objectAtIndex:0];
NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:
hmodel.Ad, #"PATIENT",
self.resultText1.text, #"WORD1",
self.resultText2.text,#"WORD2",
[NSString stringWithFormat:#"%ld",(long)compareResult ],#"EQUAL",
nil];
[histList addObject:dic];
if(![word isEqual:#""])
[histList writeToFile:pathhistory atomically:TRUE];
}
}
}
- (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation{
return(YES);
}
+(void)setbarcode1:(NSString*)barcode1 barcode2:(NSString*)barcode2{
str1=barcode1;
str2=barcode2;
}
- (void)viewDidLoad{
[super viewDidLoad];
[self.resultText1 setDelegate:self];
[self.resultText2 setDelegate:self];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return true;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
//if(textField==self.resultText2 && !resultText2.isFirstResponder){
UIView *dummyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
textField.inputView = dummyView;
int i=0;
for(UIViewController *vc in self.childViewControllers)
if([vc isKindOfClass:[NumKeyboard class]])
{
i++;
break;
}
if(!i){
NumKeyboard* numKeyboard = [[NumKeyboard alloc] initWithNibName:#"NumKeyboard" bundle:nil];
[numKeyboard.view setFrame:CGRectMake(0, self.view.frame.size.height-numKeyboard.view.frame.size.height, 320, 320)];
[self.view addSubview:numKeyboard.view];
[self addChildViewController:numKeyboard];
}
[self.view reloadInputViews];
//}
}
-(void)destroyNumKeyboard {
for(UIViewController *vc in self.childViewControllers){
if([vc isKindOfClass:[NumKeyboard class]])
{
[vc willMoveToParentViewController:nil];
[vc.view removeFromSuperview];
[vc removeFromParentViewController];
[self.parentViewController reloadInputViews];
}
break;
}
/*for (NumKeyboard *numKeyboardView in self.childViewControllers) {
if(numKeyboardView){
//UIButton son obje olduğu için
//[self.view.subviews.lastObject removeFromSuperview];
for (UIButton * btn in self.view.subviews) {
if([btn isKindOfClass:[UIButton class]])
if([btn.titleLabel.text isEqualToString:#"X"]){
[btn removeFromSuperview];
break;
}
}
[numKeyboardView willMoveToParentViewController:nil];
[numKeyboardView.view removeFromSuperview];
[numKeyboardView removeFromParentViewController];
[self reloadInputViews];
break;
}
}*/
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
}
-(void) closeHastaDetail{
[self.hastadetailview setHidden:TRUE];
}
-(void) closeHastaDetailDetail{
[self.hastadetailindetailview setHidden:TRUE];
}
-(void) openHastaDetailDetail{
[self.hastadetailindetailview setHidden:FALSE];
}
/*
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField.tag==2){
NSCharacterSet* numberCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
for (int i = 0; i < [string length]; ++i)
{
unichar c = [string characterAtIndex:i];
if (![numberCharSet characterIsMember:c])
{
return NO;
}
}
}
return YES;
}*/
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
currentKey=elementName;
currentStringValue=nil;
}
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{
if(tabBar.tag == 0)
{
[self closeHastaDetail];
[self closeHastaDetailDetail];
}
}
- (NSString *)documentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) lastObject];
}
+(void)setDidCompareZero{
didCompare=0;
}
- (IBAction)closehastadetail:(id)sender {
[self.hastadetailview setHidden:TRUE];
[self performSelector:#selector(setHistorySource) withObject:nil afterDelay:0.1f];
}
- (IBAction)push_CompareBtn:(id)sender {
[self compareTwoBarcode];
}
- (IBAction) closeResult:(id)sender{
[closeResult setHidden:TRUE];
[result setHidden:YES];
if([SettingViewController getTekliCokluArama]==1){
}
}
- (IBAction)del_txt1:(id)sender {
self.resultText1.text=#"";
}
- (IBAction)del_txt2:(id)sender {
self.resultText2.text=#"";
}
- (IBAction) deleteResult:(id)sender{
//[resultImage1 setImage: [UIImage imageNamed:#"img1.png"]];
resultText1.text = #"";
//[resultImage2 setImage:[UIImage imageNamed:#"img2.png"]];
resultText2.text = #"";
}
- (IBAction) okDetailBtn:(id)sender{
[self.hastadetailindetailview setHidden:TRUE];
}
- (IBAction) showDetail:(id)sender{
[MainViewController set_from_view:0 scanner:0];
[self openHastaDetailDetail];
}
- (IBAction)setHastaDetail:(id)sender {
[self closeHastaDetailDetail];
self.hastadetailview.contentSize =CGSizeMake(320, 600);
[self.hastadetailview setContentOffset:CGPointMake(self.hastadetailview.contentOffset.x, 0)
animated:YES];
if(hasta==nil)
hasta=[[HastaModel alloc]init];
if([self.resultText1.text length]>0){
NSMutableArray *arr=[HastaDAO getHasta:[self.resultText1.text intValue] yatanAyaktan:1];
if(![arr count] && ![self.resultText1.text isEqualToString:self.hastaProtokol.text])
arr=[HastaDAO getHasta:[self.resultText1.text intValue] yatanAyaktan:0];
if([arr count])
{
hasta =[arr objectAtIndex:0];
if(![self.resultText1.text isEqualToString:self.hastaProtokol.text])
yatanHastaBilgisi=[YatanHastaBilgileriDAO yatanHastaBilgileri:hasta.Id];
self.hastaAd.text=hasta.Ad;
self.hastaAd.textAlignment=NSTextAlignmentRight;
self.hastaAd.font=[UIFont systemFontOfSize:18];
self.hastaProtokol.text=[NSString stringWithFormat:#"%ld", (long)hasta.Id];
self.hastaBolum.text=hasta.Bolum;
self.hastaOda.text=hasta.Oda;
self.hastaCinsiyet.text=hasta.Cinsiyet;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *strDate = [dateFormatter stringFromDate:yatanHastaBilgisi.DogumTarihi];
self.hastaDogumTarihi.text=strDate;
self.hastaYatak.text=hasta.Yatak;
self.hastaDoktor.text=yatanHastaBilgisi.Doktor;
if(hasta.LastOrderId>0)
{
NSMutableArray *arr1= [AlerjiDAO alerji:0 orderId:hasta.LastOrderId];
NSString*hAlerji=#"";
for(AlerjiModel *item in arr1 )
{
if(![hAlerji isEqualToString:#""])
hAlerji=[NSString stringWithFormat:#"%#,%#",hAlerji,item.Ad];
else
hAlerji=item.Ad;
}
self.hastaAlerji.text = hAlerji;
}else
self.hastaAlerji.text =#"";
[self.hastadetailview setHidden:FALSE];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#""
message:#"Hasta bulunamadı."
delegate:nil
cancelButtonTitle:#"Tamam"
otherButtonTitles:nil];
[alert show];
}
}
}#end

I am getting an unauthorized error quickblox

I have the following code using quickblox.
Unfortunately, when I accessthe view controller, I get an "unAuthorized" error from quickblox API.
What am I doing wrong?
#import "QChatViewController.h"
#include "ChatMessageTableViewCell.h"
#interface QChatViewController ()
#end
#implementation QChatViewController
#synthesize opponent;
#synthesize currentRoom;
#synthesize messages;
#synthesize toolBar;
#synthesize sendMessageField;
#synthesize sendMessageButton;
#synthesize tableView;
#pragma mark -
#pragma mark View controller's lifecycle
- (id) initWithStartup: (NSDictionary *) _startup investor: (NSDictionary *) _investor chat_id: (NSInteger) _chat_id chat_name: (NSString *) _name
{
self = [self initWithNibName: #"QChatViewController" bundle: nil];
if(self)
{
startup = _startup;
investor = _investor;
startup_id = 0;
investor_id = 0;
if ([startup objectForKey: #"id"] &&
[startup objectForKey: #"id"] != (id)[NSNull null])
{
startup_id = [[startup objectForKey: #"id"] intValue];
}
if ([investor objectForKey: #"id"] &&
[investor objectForKey: #"id"] != (id)[NSNull null])
{
investor_id = [[investor objectForKey: #"id"] intValue];
}
past = 0;
chat_id = _chat_id;
self.title = _name;
self.title = #"Chat";
UIButton * button4 = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage * btnImage = [UIImage imageNamed: #"chatrightbtn.png"];
[button4 setFrame:CGRectMake(-90.0f, 0.0f, btnImage.size.width, btnImage.size.height)];
[button4 addTarget:self action:#selector(showSheet:) forControlEvents:UIControlEventTouchUpInside];
[button4 setImage: btnImage forState:UIControlStateNormal];
UIBarButtonItem *random1 = [[UIBarButtonItem alloc] initWithCustomView:button4];
self.navigationItem.rightBarButtonItem = random1;
self.navigationItem.leftBarButtonItem.title = #"";
}
return self;
}
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear: animated];
QBASessionCreationRequest *extendedAuthRequest = [QBASessionCreationRequest request];
extendedAuthRequest.userLogin = #"testjk";
extendedAuthRequest.userPassword = #"jerry";
[QBAuth createSessionWithExtendedRequest:extendedAuthRequest delegate:self];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBarHidden = NO;
if(chat_id >= 1) {
NSString * roomName = [NSString stringWithFormat: #"%d", chat_id];
[[QBChat instance] createOrJoinRoomWithName: roomName membersOnly:YES persistent:NO];
}
messages = [[NSMutableArray alloc] init];
}
-(void) chatDidLogin{
// You have successfully signed in to QuickBlox Chat
}
- (void)completedWithResult:(Result *)result{
// Create session result
if(result.success && [result isKindOfClass:QBAAuthSessionCreationResult.class]){
// You have successfully created the session
QBAAuthSessionCreationResult *res = (QBAAuthSessionCreationResult *)result;
// Sign In to QuickBlox Chat
QBUUser *currentUser = [QBUUser user];
currentUser.ID = res.session.userID; // your current user's ID
currentUser.password = #"jerry"; // your current user's password
// set Chat delegate
[QBChat instance].delegate = self;
// login to Chat
[[QBChat instance] loginWithUser:currentUser];
}
}
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
// leave room
if(self.currentRoom){
if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound) {
// back button was pressed.
[[QBChat instance] leaveRoom:self.currentRoom];
[[DataManager shared].rooms removeObject:self.currentRoom];
}
}
}
- (void)viewDidUnload{
[self setToolBar:nil];
[self setSendMessageField:nil];
[self setSendMessageButton:nil];
[self setTableView:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)dealloc {
}
- (IBAction)sendMessage:(id)sender {
if(self.sendMessageField.text.length == 0){
return;
}
if(chat_id == 0)
{
NSString * sid = [NSString stringWithFormat: #"%d", startup_id];
NSString * iid = [NSString stringWithFormat: #"%d", investor_id];
NSString * pasts = [NSString stringWithFormat: #"%d", past];
NSString * chat_ids = [NSString stringWithFormat: #"%d", chat_id];
NSString * path_str = [NSString stringWithFormat: #"chats/?format=json"];
NSMutableDictionary* params =[NSMutableDictionary dictionaryWithObjectsAndKeys:
sid, #"startup",
iid, #"investor",
pasts, #"past",
chat_ids, #"conversation_id",
#"avv7ejtaegxxk2wzgnymsj8xtm2tk9s4xgp6854r6dqn8bk6jjwux4g9dh9b", #"apikey",
nil];
[[API sharedInstance] postcommandWithParams:params
path: path_str
onCompletion:^(NSDictionary *json)
{
if(chat_id == 0)
{
if ([json objectForKey: #"id"] &&
[json objectForKey: #"id"] != (id)[NSNull null])
{
chat_id = [[json objectForKey: #"id"] intValue];
if(chat_id >= 1) {
NSString * roomName = [NSString stringWithFormat: #"%d", chat_id];
[[QBChat instance] createOrJoinRoomWithName: roomName membersOnly:YES persistent:NO];
}
[[QBChat instance] sendMessage:self.sendMessageField.text toRoom:self.currentRoom];
// reload table
[self.tableView reloadData];
// hide keyboard & clean text field
[self.sendMessageField resignFirstResponder];
[self.sendMessageField setText:nil];
}
}
}];
}
else
{
[[QBChat instance] sendMessage:self.sendMessageField.text toRoom:self.currentRoom];
// reload table
[self.tableView reloadData];
// hide keyboard & clean text field
[self.sendMessageField resignFirstResponder];
[self.sendMessageField setText:nil];
}
}
-(void)keyboardShow{
CGRect rectFild = self.sendMessageField.frame;
rectFild.origin.y -= 215;
CGRect rectButton = self.sendMessageButton.frame;
rectButton.origin.y -= 215;
[UIView animateWithDuration:0.25f
animations:^{
[self.sendMessageField setFrame:rectFild];
[self.sendMessageButton setFrame:rectButton];
}
];
}
-(void)keyboardHide{
CGRect rectFild = self.sendMessageField.frame;
rectFild.origin.y += 215;
CGRect rectButton = self.sendMessageButton.frame;
rectButton.origin.y += 215;
[UIView animateWithDuration:0.25f
animations:^{
[self.sendMessageField setFrame:rectFild];
[self.sendMessageButton setFrame:rectButton];
}
];
}
#pragma mark -
#pragma mark TextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
[self keyboardShow];
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
[self keyboardHide];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField setText:nil];
[textField resignFirstResponder];
return YES;
}
#pragma mark -
#pragma mark TableViewDataSource & TableViewDelegate
static CGFloat padding = 20.0;
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"MessageCellIdentifier";
// Create cell
ChatMessageTableViewCell *cell = (ChatMessageTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[ChatMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
cell.accessoryType = UITableViewCellAccessoryNone;
cell.userInteractionEnabled = NO;
// Message
QBChatMessage *messageBody = [messages objectAtIndex:[indexPath row]];
// set message's text
NSString *message = [messageBody text];
cell.message.text = message;
// message's datetime
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat: #"yyyy-mm-dd HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"..."]];
NSString *time = [formatter stringFromDate:messageBody.datetime];
CGSize textSize = { 260.0, 10000.0 };
CGSize size = [message sizeWithFont:[UIFont boldSystemFontOfSize:13]
constrainedToSize:textSize
lineBreakMode:UILineBreakModeWordWrap];
size.width += (padding/2);
// Left/Right bubble
UIImage *bgImage = nil;
if ([[[DataManager shared] currentUser] ID] == messageBody.senderID || self.currentRoom) {
bgImage = [[UIImage imageNamed:#"orange.png"] stretchableImageWithLeftCapWidth:24 topCapHeight:15];
[cell.message setFrame:CGRectMake(padding, padding*2, size.width+padding, size.height+padding)];
[cell.backgroundImageView setFrame:CGRectMake( cell.message.frame.origin.x - padding/2,
cell.message.frame.origin.y - padding/2,
size.width+padding,
size.height+padding)];
cell.date.textAlignment = UITextAlignmentLeft;
cell.backgroundImageView.image = bgImage;
if(self.currentRoom){
cell.date.text = [NSString stringWithFormat:#"%d %#", messageBody.senderID, time];
}else{
cell.date.text = [NSString stringWithFormat:#"%# %#", [[[DataManager shared] currentUser] login], time];
}
} else {
bgImage = [[UIImage imageNamed:#"aqua.png"] stretchableImageWithLeftCapWidth:24 topCapHeight:15];
[cell.message setFrame:CGRectMake(320 - size.width - padding,
padding*2,
size.width+padding,
size.height+padding)];
[cell.backgroundImageView setFrame:CGRectMake(cell.message.frame.origin.x - padding/2,
cell.message.frame.origin.y - padding/2,
size.width+padding,
size.height+padding)];
cell.date.textAlignment = UITextAlignmentRight;
cell.backgroundImageView.image = bgImage;
cell.date.text = [NSString stringWithFormat:#"%# %#", self.opponent.login, time];
}
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [self.messages count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
QBChatMessage *chatMessage = (QBChatMessage *)[messages objectAtIndex:indexPath.row];
NSString *text = chatMessage.text;
CGSize textSize = { 260.0, 10000.0 };
CGSize size = [text sizeWithFont:[UIFont boldSystemFontOfSize:13]
constrainedToSize:textSize
lineBreakMode:UILineBreakModeWordWrap];
size.height += padding;
return size.height+padding+5;
}
#pragma mark -
#pragma mark QBChatDelegate
// Did receive 1-1 message
- (void)chatDidReceiveMessage:(QBChatMessage *)message{
[self.messages addObject:message];
// save message to cache if this 1-1 chat
if (self.opponent) {
[[DataManager shared] saveMessage:[NSKeyedArchiver archivedDataWithRootObject:messages]
toHistoryWithOpponentID:self.opponent.ID];
}
// reload table
[self.tableView reloadData];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[messages count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
// Did receive message in room
- (void)chatRoomDidReceiveMessage:(QBChatMessage *)message fromRoom:(NSString *)roomName{
// save message
[self.messages addObject:message];
// reload table
[self.tableView reloadData];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[messages count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
// Fired when you did leave room
- (void)chatRoomDidLeave:(NSString *)roomName{
NSLog(#"Chat Controller chatRoomDidLeave");
}
// Called in case changing occupant
- (void)chatRoomDidChangeOnlineUsers:(NSArray *)onlineUsers room:(NSString *)roomName{
NSLog(#"chatRoomDidChangeOnlineUsers %#, %#",roomName, onlineUsers);
}
- (void)chatRoomDidEnter:(QBChatRoom *)room{
NSLog(#"Private room %# was created", room.name);
// You have to retain created room if this is temporary room. In other cases room will be destroyed and all occupants will be disconnected from room
self.currentRoom = room;
// Add users to this room
NSInteger user_id = [[[[API sharedInstance] user] objectForKey: #"id"] intValue];
NSNumber *me = [NSNumber numberWithInt: user_id];
NSArray *users = [NSArray arrayWithObjects: me, nil];
[[QBChat instance] addUsers:users toRoom:room];
}
#end
I'm not sure that you have user with these credentials
extendedAuthRequest.userLogin = #"testjk";
extendedAuthRequest.userPassword = #"jerry";
I first check user exist or not modified your code like this...
//your code
.....
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear: animated];
//Create extended session request with user authorization
QBASessionCreationRequest *extendedAuthRequest = [QBASessionCreationRequest request];
//Check user exist or not
if(self.currentQBUser){
extendedAuthRequest.userLogin = #"testjk";
extendedAuthRequest.userPassword = #"testjk";
}
[QBAuth createSessionWithExtendedRequest:extendedAuthRequest delegate:self];
}
........
- (void)completedWithResult:(Result *)result{
// Create session result
if(result.success && [result isKindOfClass:QBAAuthSessionCreationResult.class]){
// Register new user
self.currentQBUser = [[QBUUser alloc] init];
user.fullName = #"Your Name";
user.login = #"testjk";
user.password = #"testjk";
user.tags = [NSMutableArray arrayWithObject:#"Chat"];
// Create user
[QBUsers signUp:user delegate:self];
// You have successfully created the session
QBAAuthSessionCreationResult *res = (QBAAuthSessionCreationResult *)result;
} else if([result isKindOfClass:[QBUUserLogInResult class]]){
if(result.success){
QBUUserLogInResult *res = (QBUUserLogInResult *)result;
//Now login to chat
// Sign In to QuickBlox Chat
QBUUser *currentUser = res.user;
currentUser.ID = #"testjk; // your current user's ID
currentUser.password = #"testjk"; // same as user id
// set Chat delegate
[QBChat instance].delegate = self;
// login to Chat
[[QBChat instance] loginWithUser:currentUser];
}
}
if (result.errors.count && (401 != result.status))
{
NSLog(#"QBErrors: %#",result.errors);
}
}
I met the same problem here. And i gave the way i made it.
error unauthorized is the user.login or user.password.
user.login can not be email address but your login username. these i do not know why.
user.password is the email address/username password.
check these informations in your User list at QuickBlox Dashboard
Hope these instructions will help.
use quickblox.min.js
var QBApp = {
appId: 123,
authKey: 'dfdgfd44444',
authSecret: 'dffdgfdg455445'
};
$(document).ready(function () {
QB.init(QBApp.appId, QBApp.authKey, QBApp.authSecret);
QB.createSession(function (err, result) {
console.log('Session create callback', err, result);
});
})
function addUser() {
var pwd, ctr, data;
ctr = document.getElementById(myForm.password);
pwd = ctr.value;
var params = { 'login': 'Rajesh', 'password': 'Pass#123' };
alert(params)
QB.users.create(params, function (err, user) {
debugger;
if (user) {
alert('Done')
//$('#output_place').val(JSON.stringify(user));
} else {
alert('Error')
//$('#output_place').val(JSON.stringify(err));
}
})}

how to change elements on UIpickerView pushing a button or pushing another button

I have an application, that in the main view, have 3 buttons, and the 2 firts buttons have to show an UIPickerView for a selection of event (one of them) and a selection of time (the second).
UIPickerViewDelegate only let me to implement the methods one time, so, how can I do for change the content of the UIPickerView.
Here is mi .m code:
#import "Home_ViewController.h"
#interface Home_ViewController ()
#end
#implementation Home_ViewController
#synthesize index,arrayHoras,arrayRutas,pickerView, rutaId, horas, botonHoras, botonRuta, hora;
- (IBAction)selectRuta:(id)sender {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
[self.view addSubview:pickerView];
[UIView commitAnimations];
[pickerView setHidden:NO];
}
- (IBAction)horasBoton:(id)sender {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
[self.view addSubview:pickerView];
[UIView commitAnimations];
[pickerView setHidden:NO];
}
- (void)viewDidLoad
{
[super viewDidLoad];
hora = 1;
arrayRutas = [[NSMutableArray alloc] init];
arrayHoras = [[NSMutableArray alloc] initWithObjects: #"1", #"2", #"3", #"4", #"5", #"6", #"7", #"8", #"9", #"10", #"11", #"12", nil];
sqlite3 *turutaDB;
NSArray *dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *databasePath = [[dirPath objectAtIndex:0] stringByAppendingPathComponent:#"turuta.db"];
NSLog(#"path de la bbdd: %#", databasePath);
if(sqlite3_open([databasePath UTF8String], &turutaDB)==SQLITE_OK) {
NSLog(#"2 Base de datos creada y abierta con exito");
} else {
NSLog(#"Ha fallado la apertura de la bbdd");
}
sqlite3_stmt *sentenciaRutas;
NSString *querySQLrutas = #"SELECT id,nombre FROM rutas";
if(sqlite3_prepare_v2(turutaDB, [querySQLrutas UTF8String], -1, &sentenciaRutas, NULL)==SQLITE_OK){
NSLog(#"Consulta preparada ok");
} else {
NSLog(#"Consulta ha fallado al preparar: %s", sqlite3_errmsg(turutaDB));
}
while (sqlite3_step(sentenciaRutas) == SQLITE_ROW) {
NSString *selectRutas = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(sentenciaRutas, 1)];
[arrayRutas addObject:selectRutas];
}
sqlite3_finalize(sentenciaRutas);
// [self.tabBarController.tabBar setHidden:YES];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if(!botonHoras.isTouchInside) {
return [arrayHoras count];
} else {
return [arrayRutas count];
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
if(!botonHoras.isTouchInside) {
return [arrayHoras objectAtIndex:row];
} else {
return [arrayRutas objectAtIndex:row];
}
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
if (!botonHoras.isTouchInside) {
horas= [[arrayHoras objectAtIndex:row] intValue];
botonHoras.titleLabel.text = [NSString stringWithFormat:#"%d Horas", horas];
[self.pickerView removeFromSuperview];
} else {
//GMSPolylineOptions *optionsLine = [GMSPolylineOptions options];
GMSMutablePath *ruta = [GMSMutablePath path];
sqlite3 *turutaDB;
NSArray *dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *databasePath = [[dirPath objectAtIndex:0] stringByAppendingPathComponent:#"turuta.db"];
NSLog(#"path de la bbdd: %#", databasePath);
if(sqlite3_open([databasePath UTF8String], &turutaDB)==SQLITE_OK) {
NSLog(#"2 Base de datos creada y abierta con exito");
} else {
NSLog(#"Ha fallado la apertura de la bbdd");
}
sqlite3_stmt *sentenciaId;
NSString *querySQLid = [NSString stringWithFormat: #"SELECT id FROM rutas WHERE nombre = '%#'", [arrayRutas objectAtIndex:row]];
if(sqlite3_prepare_v2(turutaDB, [querySQLid UTF8String], -1, &sentenciaId, NULL)==SQLITE_OK){
NSLog(#"Consulta preparada ok");
} else {
NSLog(#"Consulta ha fallado al preparar: %s", sqlite3_errmsg(turutaDB));
}
while (sqlite3_step(sentenciaId) == SQLITE_ROW) {
NSString *id = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(sentenciaId, 0)];
rutaId = [id intValue];
NSLog(#"%d",rutaId);
}
sqlite3_finalize(sentenciaId);
sqlite3_stmt *sentenciaPolyLine;
NSString *querySQLpoliline =[NSString stringWithFormat: #"SELECT coordx,coordy FROM config_ruta WHERE id_ruta = %d", rutaId];
if(sqlite3_prepare_v2(turutaDB, [querySQLpoliline UTF8String], -1, &sentenciaPolyLine, NULL)==SQLITE_OK){
NSLog(#"Consulta preparada ok");
} else {
NSLog(#"Consulta ha fallado al preparar: %s", sqlite3_errmsg(turutaDB));
}
while (sqlite3_step(sentenciaPolyLine) == SQLITE_ROW) {
NSString *x = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(sentenciaPolyLine, 1)];
NSString *y = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(sentenciaPolyLine, 0)];
double coordx = [x doubleValue];
double coordy = [y doubleValue];
NSLog(#"%f | %f",coordy,coordx);
[ruta addCoordinate:CLLocationCoordinate2DMake(coordy, coordx)];
}
sqlite3_finalize(sentenciaPolyLine);
botonRuta.titleLabel.text = [arrayRutas objectAtIndex:row];
[self.pickerView removeFromSuperview];
[pickerView selectRow:0 inComponent:0 animated:YES];
}
}
- (IBAction)rutaboton:(id)sender {
}
Some help please...
You need to set a flag indicating which button was pressed. Then you check that flag in each of the picker view data source and delegate methods.
Add an int property to your class. In the selectRuta: method set the property to 1. In the horasBoton: method, set the property to 2.
Then you picker view method look something like this (this assumes your property was named buttonType):
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if(self.buttonType == 1) {
return [arrayRutas count];
} else {
return [arrayHoras count];
}
}

Resources