Search code examples
iphonensstringlocalenon-ascii-characters

Check keyboard input for ASCII compatibility on iPhone


When user taps on keyboard, I need to know does the input symbol belong to ASCII palette, and strip it otherwise.

So what I need to do in

-(BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) string

method to check input character?

At current moment I get an ASCII characters from input string when user types with (for example) Russian language:

const char* want_strip_not_ascii_chars = [string UTF8string];

Solution

  • The following will give you what you are asking for:

    -(BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) string
    {
        return [string canBeConvertedToEncoding:NSASCIIStringEncoding];
    }
    

    Though do please consider that this will prevent users with non-ASCII keyboards from using your field.