How do I URL encode a string

前端 未结 22 1681
轮回少年
轮回少年 2020-11-22 07:16

I have a URL string (NSString) with spaces and & characters. How do I url encode the entire string (including the & ampersand

相关标签:
22条回答
  • 2020-11-22 07:56

    Use NSURLComponents to encode HTTP GET parameters:

        var urlComponents = NSURLComponents(string: "https://www.google.de/maps/")!
        urlComponents.queryItems = [
            NSURLQueryItem(name: "q", value: String(51.500833)+","+String(-0.141944)),
            NSURLQueryItem(name: "z", value: String(6))
        ]
        urlComponents.URL     // returns https://www.google.de/maps/?q=51.500833,-0.141944&z=6
    

    http://www.ralfebert.de/snippets/ios/encoding-nsurl-get-parameters/

    0 讨论(0)
  • 2020-11-22 07:56
    -(NSString *)encodeUrlString:(NSString *)string {
      return CFBridgingRelease(
                        CFURLCreateStringByAddingPercentEscapes(
                            kCFAllocatorDefault,
                            (__bridge CFStringRef)string,
                            NULL,
                            CFSTR("!*'();:@&=+$,/?%#[]"),
                            kCFStringEncodingUTF8)
                        );
    }
    

    according to the following blog

    0 讨论(0)
  • 2020-11-22 07:57

    swift code based on chown's objc answer in this thread.

    extension String {
        func urlEncode() -> String {
            return CFURLCreateStringByAddingPercentEscapes(
                nil,
                self,
                nil,
                "!*'();:@&=+$,/?%#[]",
                CFStringBuiltInEncodings.UTF8.rawValue
            )
        }
    }
    
    0 讨论(0)
  • 2020-11-22 07:57

    //This is without test

    NSMutableCharacterSet* set = [[NSCharacterSet alphanumericCharacterSet] mutableCopy];
    [set addCharactersInString:@"-_.~"];
    NSString *encode = [test stringByAddingPercentEncodingWithAllowedCharacters:set];
    
    0 讨论(0)
  • 2020-11-22 07:57

    I faced a similar problem passing complex strings as a POST parameter. My strings can contain Asian characters, spaces, quotes and all sorts of special characters. The solution I eventually found was to convert my string into the matching series of unicodes, e.g. "Hu0040Hu0020Hu03f5...." using [NSString stringWithFormat:@"Hu%04x",[string characterAtIndex:i]] to get the Unicode from each character in the original string. The same can be done in Java.

    This string can be safely passed as a POST parameter.

    On the server side (PHP), I change all the "H" to "\" and I pass the resulting string to json_decode. Final step is to escape single quotes before storing the string into MySQL.

    This way I can store any UTF8 string on my server.

    0 讨论(0)
  • 2020-11-22 08:03

    In Swift 3, please try out below:

    let stringURL = "YOUR URL TO BE ENCODE";
    let encodedURLString = stringURL.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
    print(encodedURLString)
    

    Since, stringByAddingPercentEscapesUsingEncoding encodes non URL characters but leaves the reserved characters (like !*'();:@&=+$,/?%#[]), You can encode the url like the following code:

    let stringURL = "YOUR URL TO BE ENCODE";
    let characterSetTobeAllowed = (CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted)
    if let encodedURLString = stringURL.addingPercentEncoding(withAllowedCharacters: characterSetTobeAllowed) {
        print(encodedURLString)
    }
    
    0 讨论(0)
提交回复
热议问题