String encoding for all iPhone standard keyboard characters

596 Views Asked by At

I am trying to encode a string (to send through HTTP post request) to accept all characters that can be typed on an iPhone.

The following works for any characters I try on a typical english desktop keyboard

let userPassword = "password1"
let encodedPassword = userPassword.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet())

But doesn't recognize accented characters like á, é, í, ó, ú, ü, ñ etc. (that are accessible on the standard iPhone keyboard by pressing and holding a, e, i...). Is there an NSCharacterSet or simple extension that would include any/all characters found on the standard iPhone keyboard?

EDIT: Here is the code for the request I am making

let username = "joe"
let password = "pássword"
let encodedUsername = username.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet())
let encodedPassword = password.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet())

let request = NSMutableURLRequest(URL: NSURL(string: "https://www.url.com")!)
request.HTTPMethod = "POST"
let postString = "id="+encodedUsername+"&pw="+encodedPassword
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in
    ...
1

There are 1 best solutions below

2
On

Just add this while taking user input,this way there will be no chance of user to add any special symbol or accented characters and you don't have to encode with allowed characters:-

#define ACCEPTABLE_CHARACTERS @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
         NSCharacterSet *acceptedInput = [NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS];
        if (![[string componentsSeparatedByCharactersInSet:acceptedInput] count] > 1){
            NSLog(@"not allowed");
            return NO;
        }
        else{
            return YES;
        }
}