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];
}
Related
I am using SQLite and I want to save the name, address, and phone text fields for them to show up in the next view controller for when the "show details" button is clicked in 1st VC.
I placed "save" and "show details" button in 1st VC, as well as "previous" and "next" button in 2nd VC. Whenever I click on "show details" I am getting this error message:
index 0 beyond bounds for empty array.
However, I see that the array is not empty. I want to store the student details in the array.
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *homeDirectory = NSHomeDirectory();
NSString *documentsDirectoryPath = [homeDirectory stringByAppendingPathComponent:#"Documents"];
self.dbFilePathInDocuments = [documentsDirectoryPath stringByAppendingPathComponent:#"details.db"];
self.studentDetails = [[NSMutableArray alloc]init];
NSString *selectQuery = [NSString stringWithFormat:#"select name,address,phone from contacts"];
sqlite3_open([self.dbFilePathInDocuments UTF8String], &dataBase);
sqlite3_prepare_v2(dataBase, [selectQuery UTF8String], -1,&selectStatement, NULL);
while (sqlite3_step(selectStatement) == SQLITE_ROW)
{
NSMutableDictionary *studentDict = [[NSMutableDictionary alloc]init];
NSString *name = [NSString stringWithFormat:#"%s",sqlite3_column_text(selectStatement, 0)];
NSString *address = [NSString stringWithFormat:#"%s",sqlite3_column_text(selectStatement, 1)];
NSString *phone = [NSString stringWithFormat:#"%s",sqlite3_column_text(selectStatement, 2)];
[studentDict setObject:name forKey:#"name"];
[studentDict setObject:address forKey:#"address"];
[studentDict setObject:phone forKey:#"phone"];
[self.studentDetails addObject:studentDict];
NSLog(#"student is:%#",self.studentDetails);
}
sqlite3_finalize(selectStatement);
sqlite3_close(dataBase);
self.nameLabel.text = [[self.studentDetails objectAtIndex:0] valueForKey:#"name"];
self.addressLabel.text = [[self.studentDetails objectAtIndex:0] valueForKey:#"address"];
self.phoneLabel.text = [[self.studentDetails objectAtIndex:0] valueForKey:#"phone"];
currentStudentIndex = 0;
}
- (IBAction)clickPrevious:(id)sender {
if(currentStudentIndex <=0)
{
currentStudentIndex = 0;
}else
{
currentStudentIndex = currentStudentIndex - 1;
}
self.nameLabel.text = [[self.studentDetails objectAtIndex:currentStudentIndex] valueForKey:#"name"];
self.addressLabel.text = [[self.studentDetails objectAtIndex:currentStudentIndex] valueForKey:#"address"];
self.phoneLabel.text = [[self.studentDetails objectAtIndex:currentStudentIndex] valueForKey:#"phone"];
}
- (IBAction)clickNext:(id)sender {
if(currentStudentIndex >= [self.studentDetails count] - 1)
{
currentStudentIndex = [self.studentDetails count] - 1;
}else
{
currentStudentIndex = currentStudentIndex + 1;
}
self.nameLabel.text = [[self.studentDetails objectAtIndex:currentStudentIndex] valueForKey:#"name"];
self.addressLabel.text = [[self.studentDetails objectAtIndex:currentStudentIndex] valueForKey:#"address"];
self.phoneLabel.text = [[self.studentDetails objectAtIndex:currentStudentIndex] valueForKey:#"phone"];
}
The issue is that you always accessing the array self.studentDetails even if it's empty. This will cause an exception.
First limit setting of the labels to a single method and check the array access will succeed before attempting it:
- (void)updateLabels
{
if (currentStudentIndex >= [self.studentDetails count])
return;
self.nameLabel.text = [[self.studentDetails objectAtIndex:currentStudentIndex] valueForKey:#"name"];
self.addressLabel.text = [[self.studentDetails objectAtIndex:currentStudentIndex] valueForKey:#"address"];
self.phoneLabel.text = [[self.studentDetails objectAtIndex:currentStudentIndex] valueForKey:#"phone"];
}
and use that method in the 3 places you currently set the labels. For example:
- (IBAction)clickPrevious:(id)sender {
currentStudentIndex--;
[self updateLabels];
}
- (IBAction)clickNext:(id)sender {
currentStudentIndex++;
[self updateLabels];
}
In the viewDidLoad method use this code:
...
sqlite3_finalize(selectStatement);
sqlite3_close(dataBase);
currentStudentIndex = 0;
[self updateLabels];
After that you're gonna want to work on enabling/disabling buttons depending on whether there is a next or previous student to view to make using the app more intuitive.
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
i need to send in one package two float numbers. I use CocoaOSC project https://github.com/danieldickison/CocoaOSC
how i call function to send:
[delegate sendPacket:#"/ShotHappends" value:[NSString stringWithFormat:#"%.3f %.3f", myXRound, myYRound] type:2];
my function
- (void)sendPacket:(NSString*)address value:(NSString*)sendValue type:(int)type
{
defaults = [NSUserDefaults standardUserDefaults];
remoteHost = [defaults stringForKey:#"host"];
remotePort = [defaults stringForKey:#"port"];
NSLog(#"Value: %#", sendValue);
OSCMutableMessage *message = [[OSCMutableMessage alloc] init];
message.address = address;
sendType = type;
switch (sendType)
{
case 0: [message addString:sendValue]; break;
case 1: [message addInt:[sendValue intValue]]; break;
case 2: [message addFloat:[sendValue floatValue]]; break;
case 3: [message addBlob:[sendValue dataUsingEncoding:NSUTF8StringEncoding]]; break;
case 4: [message addTimeTag:[NSDate date]]; break;
case 5: [message addBool:YES]; break;
case 6: [message addBool:NO]; break;
case 7: [message addImpulse]; break;
case 8: [message addNull]; break;
}
[connection sendPacket:message toHost:remoteHost port:[remotePort intValue]];
}
so as you see i create a string and say in my function what is in these string, if i say that string #"0,22 0,45" is float my server will get only first number, so how can i send two floats to my server? Thank you.
I haven't tested this, or even read the API, but I would imagine you would have to create a version of your method that accepts arrays of type/values:
- (void)sendPacket:(NSString*)address
values:(NSArray*)values
types:(NSArray*)types
{
NSAssert([values count] == [types count], #"Values/types array are different sizes!");
defaults = [NSUserDefaults standardUserDefaults];
remoteHost = [defaults stringForKey:#"host"];
remotePort = [defaults stringForKey:#"port"];
OSCMutableMessage *message = [[OSCMutableMessage alloc] init];
message.address = address;
for (NSUInteger i = 0; i < [values count]; i++)
{
int sendType = [[types objectAtIndex:i] intValue];
id sendValue = [values objectAtIndex:i];
switch (sendType)
{
case 0: [message addString:sendValue]; break;
case 1: [message addInt:[sendValue intValue]]; break;
case 2: [message addFloat:[sendValue floatValue]]; break;
case 3: [message addBlob:[sendValue dataUsingEncoding:NSUTF8StringEncoding]]; break;
case 4: [message addTimeTag:[NSDate date]]; break;
case 5: [message addBool:YES]; break;
case 6: [message addBool:NO]; break;
case 7: [message addImpulse]; break;
case 8: [message addNull]; break;
}
}
[connection sendPacket:message toHost:remoteHost port:[remotePort intValue]];
}
Note: as you are passing the types (int) in an Objective-C collection class, they must be wrapped in NSNumber objects:
[delegate sendPacket:#"/ShotHappends"
values:#[[NSString stringWithFormat:#"%.3f", myXRound],
[NSString stringWithFormat:#"%.3f", myYRound]
]
types:#[ #(2), #(2) ]
];
Note 2: An improvement to your method would be to pass strings as NSString, numbers/bools as NSNumber and data as NSData rather than using NSString all the time. Up to you, though.
My app has an action button to pull up a UIActivityViewController. On my test device 5S, it will do everything fine, including texting. However, on my 5C test device, it crashes upon trying to send a Message. Is there something wrong with my code here that would make it work with SOME phones for sending Message, and not others?
The code listed below has some caveats to it. First of all, some times, the text to be sent will be over 140 characters, so I run a check first on the length of the string. If over 140 characters, it clips out middle part, adds ... before the end, and keeps it at 140 characters. Then, on the action, if over 140 characters it sends the edited string just for Twitter and Message, but the regular string for all others, and regular string, if 140 characters or under.
-(void)sendit {
NSString *string = label1.text;
if ([string length] > 140) {
int maxChars = 140;
int charsOver = [string length] - maxChars;
NSString *replacementString = #"...";
charsOver += [replacementString length]; //account for adding "..."
NSArray *components = [string componentsSeparatedByString:#" - "];
NSMutableString *stringToTrim = [NSMutableString string];
int numberOfComponents = [components count];
for (int i = 0; i < numberOfComponents - 1; i++) {
NSString *component = [components objectAtIndex:i];
if (i < numberOfComponents - 2) {
[stringToTrim appendFormat:#"%# - ", component];
}
else {
[stringToTrim appendString:component];
}
}
NSString *trimmedString = [stringToTrim substringToIndex:[stringToTrim length] - charsOver];
self.finalString = [NSString stringWithFormat:#"%#%#%#", [trimmedString stringByAppendingString:replacementString], #" - ", [components objectAtIndex:numberOfComponents - 1]];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:#[self] applicationActivities:nil];
activityVC.excludedActivityTypes = #[ UIActivityTypePostToWeibo,
UIActivityTypeAssignToContact,
UIActivityTypePrint,
UIActivityTypeAirDrop
];
[self presentViewController:activityVC animated:YES completion:nil];
}
else {
NSArray *activityItems = #[label1.text];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
activityVC.excludedActivityTypes = #[ UIActivityTypePostToWeibo,
UIActivityTypeAssignToContact,
UIActivityTypePrint,
UIActivityTypeAirDrop
];
[self presentViewController:activityVC animated:YES completion:nil];
}
}
- (id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType {
if ([activityType isEqualToString:UIActivityTypeMail]) {
NSLog(#"TEST");
return label1.text;
}
if ([activityType isEqualToString:UIActivityTypePostToTwitter]){
NSString *string = label1.text;
if ([string length] > 140) {
return self.finalString;
}
else {
return label1.text;
}
}
if ([activityType isEqualToString:UIActivityTypePostToFacebook]){
return label1.text;
}
if ([activityType isEqualToString:UIActivityTypeCopyToPasteboard]){
return label1.text;
}
if ([activityType isEqualToString:UIActivityTypeMessage]){
NSString *string = label1.text;
if ([string length] > 140) {
return self.finalString;
}
else {
return label1.text;
}
}
return nil;
}
I have created a code for Addressbook and contacts where display the contacts.It was working properly but suddenly getting Run time error .As I'm new to ios .I'm not able to find the error can any one in the Stack Overflow tell the error.
- (void)viewDidLoad
{
[super viewDidLoad];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view.backgroundColor = [UIColor yellowColor];
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:#selector(gotohomepage:)]autorelease];
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
[[picker navigationBar] setBarStyle:UIBarStyleBlack];
picker.peoplePickerDelegate = self;
// Display only a person's phone, email, and birthdate
NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty],nil];
picker.displayedProperties = displayedItems;
[self presentModalViewController:picker animated:YES];
[picker release];
}
- (IBAction)gotohomepage:(id)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
ABAddressBookRef addressBook = ABAddressBookCreate();
int i;
NSString *strName = #"";
NSString* company = #"";
NSString *address = #"";
NSString *suburb = #"";
NSString *postalcode = #"";
NSString *state = #"";
NSString *country = #"";
NSString *mobile = #"";
NSString *phone = #"";
NSString *emailid = #"";
strName = (NSString *)ABRecordCopyCompositeName((ABRecordRef) person);
CFStringRef name = ABRecordCopyCompositeName((ABRecordRef) person);
company = (NSString *)ABRecordCopyValue((ABRecordRef) person, kABPersonOrganizationProperty);
NSArray* allPeople = (NSArray *)ABAddressBookCopyPeopleWithName(addressBook,name);
CFRelease(name);
for (i = 0; i < [allPeople count]; i++)
{
ABRecordRef record = [allPeople objectAtIndex:i];
ABMutableMultiValueRef multiValue = ABRecordCopyValue(record, kABPersonAddressProperty);
for(CFIndex i=0; i<ABMultiValueGetCount(multiValue); i++)
{
NSString* HomeLabel = (NSString*)ABMultiValueCopyLabelAtIndex(multiValue, i);
if([HomeLabel isEqualToString:#"_$!<Home>!$_"])
{
CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(multiValue, i);
address = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStreetKey)];
suburb = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCityKey)];
postalcode = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressZIPKey)];
state = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStateKey)];
country = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCountryKey)];
CFRelease(dict);
}
CFRelease(HomeLabel);
}
CFRelease(multiValue);
}
CFRelease(allPeople);
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* mobileLabel = nil;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
{
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",mobile);
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
phone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",phone);
CFRelease(mobileLabel);
break ;
}
CFRelease(mobileLabel);
}
CFStringRef value, label;
ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex count = ABMultiValueGetCount(multi);
if (count == 1)
{
value = ABMultiValueCopyValueAtIndex(multi, 0);
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
CFRelease(value);
}
else
{
for (CFIndex i = 0; i < count; i++)
{
label = ABMultiValueCopyLabelAtIndex(multi, i);
value = ABMultiValueCopyValueAtIndex(multi, i);
// check for Work e-mail label
if (CFStringCompare(label, kABWorkLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
else if(CFStringCompare(label, kABHomeLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
CFRelease(label);
CFRelease(value);
}
}
CFRelease(multi);
CFRelease(phones);
CFRelease(addressBook);
[self dismissModalViewControllerAnimated:YES];
return NO;
}
On iOS6, apple introduce new privacy control, user can control the accessment of contact and calender by each app. So, in the code side, you need to add some way to request the permission. In iOS5 or before, we can always call
ABAddressBookRef addressBook = ABAddressBookCreate();
to get the addressbook without any problem, but in iOS6, if you don't have permission, this call will just return empty pointer. That why we need to change the method to get ABAddressBookRef.
This type of error generally appears when permission is not granted to access address book.In that case please add this piece of code
__block BOOL accessGranted = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS 6
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
accessGranted = granted;
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_release(sema);
}
else { // we're on iOS 5 or older
accessGranted = YES;
}
if (accessGranted) {
// Do whatever you want here.
}
courtesy :- http://programmerjoe.blogspot.in/2012/10/ios6-permissions-contacts.html
If this doesn't solves your problem ping me back..
Error is that, because on IOS6 , Apple added some features that no one have permissions to get contents without owner's permission.