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.
Related
i made a random for A-Z. The random letter is shown in a label. everything works fine. But the letter should not repeat till every letter from A-Z is called.
I´am new in xcode an need a litte help.
heres my code in the .m file.
NSString *letters = #"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-(NSString *) randomStringWithLength:(int) len {
NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
for (int i=26; i<len; i++) {
[randomString appendFormat: #"%C", [letters characterAtIndex: arc4random() % [letters length]]]; buchstabeAusgabe.text = randomString;
}
return randomString;}
-(void)neuerGenerator {
int text = rand() %26;
switch (text) {
case 0:
buchstabeAusgabe.text =#"A";
break;
case 1:
buchstabeAusgabe.text =#"B";
break;
case 2:
buchstabeAusgabe.text =#"C";
break;
case 3:
buchstabeAusgabe.text =#"D";
break;
case 4:
buchstabeAusgabe.text =#"E";
break;
case 5:
buchstabeAusgabe.text =#"F";
break;
case 6:
buchstabeAusgabe.text =#"G";
break;
case 7:
buchstabeAusgabe.text =#"H";
break;
case 8:
buchstabeAusgabe.text =#"I";
break;
case 9:
buchstabeAusgabe.text =#"J";
break;
case 10:
buchstabeAusgabe.text =#"K";
break;
case 11:
buchstabeAusgabe.text =#"L";
break;
case 12:
buchstabeAusgabe.text =#"M";
break;
case 13:
buchstabeAusgabe.text =#"N";
break;
case 14:
buchstabeAusgabe.text =#"O";
break;
case 15:
buchstabeAusgabe.text =#"P";
break;
case 16:
buchstabeAusgabe.text =#"Q";
break;
case 17:
buchstabeAusgabe.text =#"R";
break;
case 18:
buchstabeAusgabe.text =#"S";
break;
case 19:
buchstabeAusgabe.text =#"T";
break;
case 20:
buchstabeAusgabe.text =#"U";
break;
case 21:
buchstabeAusgabe.text =#"V";
break;
case 22:
buchstabeAusgabe.text =#"W";
break;
case 23:
buchstabeAusgabe.text =#"X";
break;
case 24:
buchstabeAusgabe.text =#"Y";
break;
case 25:
buchstabeAusgabe.text =#"Z";
break;
default:
break;
}}
instead of the switch, perhaps store the alphabet in an NSMutableArray. When a letter is taken, remove it from the array. Instead of %26 do %[array count]. To look up the item in array, use [array objectAtIndex:index] where index is the random number.
I am not on XCode at the moment, but I'll try to write out the full code:
- (NSString *) randomStringWithLength:(int) len andAlphabet: (NSString *) alphabet {
NSMutableArray *alphabetArrayMut = [[self arrayFromString: alphabet] mutableCopy];
NSMutableString *resultString = [NSMutableString stringWithString:#""];
while([alphabetArrayMut count]&&[resultString length]<len){
int index = rand() % [alphabetArrayMut count];
NSString *charToAdd = [alphabetArrayMut objectAtIndex:index];
[resultString appendString:charToAdd];
[alphabetArrayMut removeObjectAtIndex:index];
}
return [resultString copy];
}
- (NSArray *) arrayFromString: (NSString *) string{
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[string length]];
for (int i=0; i < [string length]; i++) {
NSString *ichar = [NSString stringWithFormat:#"%c", [string characterAtIndex:i]];
[characters addObject:ichar];
}
return [characters copy];
}
Note that it is probably a lot easier to use recursion. Unfortunately, I am not on my mac at the moment, so I can't test it:
- (NSString *) randomStringWithLength:(int) len andAlphabet: (NSString *) alphabet {
if(len <= 0 || ![alphabet count]){ // base case
return #"";
}
int index = rand() % [alphabet count];
NSString *chosenLetter = [alphabet substringWithRange:NSMakeRange(index, 1)];
NSString *newAlphabet = [alphabet stringByReplacingCharactersInRange:NSMakeRange(index, 1) withString:#""];
NSString *resultString = [NSString stringWithFormat:#"%#%#",chosenLetter,[self randomStringWithLength:len-1,newAlphabet];
return resultString;
}
Lots of different ways to do this. My suggestion would be to use a mutable array:
Add this statement to your .h file:
NSMutableArray *randomLetters;
And then add this method to your .m file:
(Code edited to clean up a ton of typos and minor mistakes)
- (NSString *) randomLetter;
{
if (randomLetters == nil)
randomLetters = [NSMutableArray arrayWithCapacity: 26];
if (randomLetters.count == 0)
{
for (unichar aChar = 'A'; aChar <= 'Z'; aChar++)
{
[randomLetters addObject: [NSString stringWithCharacters: &aChar length: 1]];
}
}
NSUInteger randomIndex = arc4random_uniform((u_int32_t)randomLetters.count);
NSString *result = randomLetters[randomIndex];
[randomLetters removeObjectAtIndex: randomIndex];
return result;
}
(Disclaimer: I typed that code out in the SO editor. I haven't tried to compile it, so it may contain minor typos.)
The method randomLetter will give you a single, non-repeating random letter every time you call it, until the array of remaining random letters is empty. At that point it will repopulate the array with the full alphabet and start over.
The random number generator arc4random_uniform() gives much better results that rand(), and doesn't suffer from "modulo bias" (link) like the expression rand()%range does.
Note that it is possible for the above method to give you the last random letter (an "a", for example") then on the next call, repopulate the array, and give you another "a" from the newly populated array. However, the odds of that happening are only 1 in 26.
You could tweak the above code so it remembers the last character it gives you and doesn't give you that same character twice in a row if that's important.
You could pretty easily change it slightly so that it would give you letters one at a time until it's empty and then return nil, and then write a separate method to fill it. That way you could get exactly 26 non-repeating characters and know when you about to repeat with another set of 26 characters.
because c string is terminal by '\0', we need 27 bytes.
NSString *alp = #"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char cstr[27];
[alp getCString:cstr maxLength:27 encoding:NSUTF8StringEncoding];
// do i from 25 to 0. to 1 is ok, also
for (int i = alp.length - 1; i >= 0; --i) {
int mark = arc4random_uniform(i);
char temp = cstr[i];
cstr[i] = cstr[mark];
cstr[mark] = temp;
}
NSString *str = [NSString stringWithUTF8String:cstr];
NSLog(#"%#", str);
Given these methods:
- (NSString *)stringOfRandomLettersWithLength:(NSUInteger)length {
if (length > 26) {
return nil;
}
NSMutableString *stringOfRandomLetters = [NSMutableString stringWithCapacity:length];
NSArray *letters = #[ #"A", #"B", #"C", #"D", #"E", #"F", #"G", #"H", #"I", #"J", #"K", #"L", #"M", #"N", #"O", #"P", #"Q", #"R", #"S", #"T", #"U", #"V", #"W", #"X", #"Y", #"Z" ];
NSMutableArray *unusedLetters = [letters mutableCopy];
NSString *randomLetter;
for (int i=0; i<length; i++) {
randomLetter = [self randomItemFromArray:unusedLetters];
[unusedLetters removeObject:randomLetter];
[stringOfRandomLetters appendString:randomLetter];
}
return stringOfRandomLetters;
}
- (NSString *)randomItemFromArray:(NSArray *)items {
if (items.count < 1) {
return nil;
}
return items[ arc4random_uniform((u_int32_t)items.count) ];
}
You could create a string of random, distinct letters like this:
NSString *label = [self stringOfRandomLettersWithLength:26];
NSLog(#"label= %#", label);
In the console you'd see something like this:
label= YGRHCXTFDZLKNPAIEOJSUQWVMB
I have an array of lattitudes and longitudes in my array,
NSArray *anArrayOfFloatObjects = [NSArray arrayWithObjects:
[NSNumber numberWithDouble:pinLocation1.latitude],
[NSNumber numberWithDouble:pinLocation1.longitude],
[NSNumber numberWithDouble:pinLocation2.latitude],
[NSNumber numberWithDouble:pinLocation2.longitude],
[NSNumber numberWithDouble:pinLocation3.latitude],
[NSNumber numberWithDouble:pinLocation3.longitude],
nil];
What I want to do is use a switch statement to go through the array (i.e. objectAtIndex..)
switch (self.anArrayOfFloatObjects objectAtIndex:) {
case :0
//switch the pin color to red
break;
case :2
//switch pin color to green
break;
default:
break;
}
This obviously doesnt work. Does anyone know any other way?
I believe what you are looking for is
[anArrayOfFloatObjects indexOfObject:number]
Maybe this code will help:
NSArray *anArrayOfFloatObjects; //Your array
for (NSNumber *number in anArrayOfFloatObjects) {
switch ([anArrayOfFloatObjects indexOfObject:number]) {
case :0
//switch the pin color to red
break;
case :2
//switch pin color to green
break;
default:
break;
}
}
EDIT:
Following #MikeS comment you can do something like this:
for (int index = 0; index < [anArrayOfFloatObjects count]; index++) {
switch (index) {
case :0
//switch the pin color to red
break;
case :2
//switch pin color to green
break;
default:
break;
}
}
Avoiding the need of calling [anArrayOfFloatObjects indexOfObject:number]
try fast enumeration
for(id item in anArrayOfFloatObjects){
NSLog(#"%#", item);
}
You can also look into NSArray's enumerateObjectsUsingBlock.
[yourArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"Index: %ld - Object: %#", idx, obj);
}];
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];
}
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 have an app that uses sockets to send login information to a server and receives a response in form of a contact list. This is the main method for processing responses from server:
-(void) stream:(NSStream*)theStream handleEvent:(NSStreamEvent)streamEvent {
switch(streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(#"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if(theStream == inputStream) {
uint8_t buffer[8196];
int len;
while([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if(len>0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding];
if(output != nil) {
NSLog(#"server said: %#", output);
id jsonOutput = [self createJsonFromString:output];
if([[jsonOutput objectForKey:#"msg_type"] isEqualToString:#"LoginResponse"])
{
[self sendMessage:[self createAddressBookRequestJsonData]];
} else if ([[jsonOutput objectForKey:#"msg_type"] isEqualToString:#"GetAddressBookResponse"])
{
id contactList = [jsonOutput objectForKey:#"contact_list"];
for(id contactListItem in contactList)
{
XYZAddressBookEntry *newEntry = [[XYZAddressBookEntry alloc] init];
newEntry.firstName = [contactListItem objectForKey:#"FirstName"];
newEntry.lastName = [contactListItem objectForKey:#"LastName"];
newEntry.displayName = [contactListItem objectForKey:#"DisplayName"];
newEntry.softphoneNumber = [contactListItem objectForKey:#"SoftphoneNumber"];
newEntry.homeNumber = [contactListItem objectForKey:#"HomeNumber"];
newEntry.mobileNumber = [contactListItem objectForKey:#"MobileNumber"];
newEntry.businessNumber = [contactListItem objectForKey:#"BusinessNumber"];
newEntry.name = [contactListItem objectForKey:#"Name"];
newEntry.phoneAddress = [contactListItem objectForKey:#"PhoneAddress"];
[self.entryList addObject:newEntry];
}
[self.tableView reloadData];
}
}
}
}
}
break;
case NSStreamEventHasSpaceAvailable:
break;
case NSStreamEventEndEncountered:
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
break;
case NSStreamEventErrorOccurred:
NSLog(#"Can not connect to the host!");
break;
default:
NSLog(#"Unknown event:");
} }
I always get a correct output in my log, so everything goes smooth, but if I don't set a breakpoint right after NSLog(#"server said: %#", output), it will not enter the if else code block. What am I missing?
By the way, I'm a newbie to this, started using objective-c just 2 weeks ago.