0

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
    ...
Tamarisk
  • 929
  • 2
  • 11
  • 27
  • What do you mean by "doesn't recognize"? How are you building the request? – jtbandes Jan 29 '16 at 08:46
  • You should use NSCharacterSet URL Query Allowed Character Set – Leo Dabus Jan 29 '16 at 08:52
  • @LeoDabus I believe NSCharacterSet.URLQueryAllowedCharacterSet() still doesn't include some characters (& and + I believe). I also just tried it for a string containing an accented character and it didn't work – Tamarisk Jan 29 '16 at 09:09

1 Answers1

0

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;
        }
}
Vizllx
  • 9,135
  • 1
  • 41
  • 79
  • The question is tagged "swift", please post a Swift answer, not Objective-C. Thanks! – Eric Aya Jan 29 '16 at 09:00
  • For Swift:---- http://stackoverflow.com/questions/1656410/strip-non-alphanumeric-characters-from-an-nsstring/26337774#26337774 This is for my friend @EricD. ;) – Vizllx Jan 29 '16 at 09:36