Yomo Yomo - 20 days ago 11
Objective-C Question

Buddy name in SMS? (Obj-C)

I'm making an app where the user can send a SMS with prefilled phone numbers. loadString, loadString2, and loadString3 are strings for UITextFields which the user can fill in and save. However, if the user only fills in one or two fields, and leaves one empty, the recipients are the chosen phone numbers, and one contact called Buddy name.

My question is, how do I get rid of this strange contact, called "Buddy name"?

My code:

if ([MFMessageComposeViewController canSendText])

{

[controller setRecipients:[NSArray arrayWithObjects:loadString, loadString2, loadString3, nil]];
[controller setBody:theLocation];
[self presentViewController:controller animated:YES completion:NULL];

} else {
NSLog(@"Can't open text.");
}

Answer

"Buddy Name" shows if the array contains a string that isn't a valid contact like the empty string. Only add the strings to the recipients array if they are non-empty:

if ([MFMessageComposeViewController canSendText])
{
    NSMutableArray *recipents = [NSMutableArray array];
    if ([self isValidPhoneNumber:loadString]) {
         [recipents addObject:loadString];
    }
    if ([self isValidPhoneNumber:loadString2]) {
         [recipents addObject:loadString2];
    }
    if ([self isValidPhoneNumber:loadString3]) {
         [recipents addObject:loadString3];
    }
    [controller setRecipients:recipents];
    [controller setBody:theLocation];
    [self presentViewController:controller animated:YES completion:NULL];

} else {
    NSLog(@"Can't open text.");
}

...

- (BOOL)isValidPhoneNumber:(NSString *)phoneNumberString {
    // If the length is 0 it's invalid. You may want to add other checks here to make sure it's not invalid for other reasons.
    if (phoneNumberString.length == 0) {
        return NO;
    } else {
        return YES;
    }
}