Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URLEncoding from Objc to Swift 3

We are using following URL encoding in Objective C now we are migrating to swift .what will be the equivalent encoding for below ObjC to swift 3.

- (NSString *) URLEncodedString {
    NSMutableString * output = [NSMutableString string];
    const unsigned char * source = (const unsigned char *)[self UTF8String];
    int sourceLen = strlen((const char *)source);
    for (int i = 0; i < sourceLen; ++i) {
        const unsigned char thisChar = source[i];
        if (thisChar == ' '){
            [output appendString:@"+"];
        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' || 
                   (thisChar >= 'a' && thisChar <= 'z') ||
                   (thisChar >= 'A' && thisChar <= 'Z') ||
                   (thisChar >= '0' && thisChar <= '9')) {
            [output appendFormat:@"%c", thisChar];
        } else {
            [output appendFormat:@"%%%02X", thisChar];
        }
    }
    return output;
}
like image 394
AppleBee Avatar asked Feb 19 '26 17:02

AppleBee


1 Answers

This code should generate exactly the same result as your Objective-C code. (Should compile and work as expected in both Swift 3 and 4.)

extension String {
    var urlEncoded: String {
        var output = ""
        for thisChar in self.utf8 {
            switch thisChar {
            case UInt8(ascii: " "):
                output.append("+")
            case UInt8(ascii: "."), UInt8(ascii: "-"), UInt8(ascii: "_"), UInt8(ascii: "~"),
                 UInt8(ascii: "a")...UInt8(ascii: "z"),
                 UInt8(ascii: "A")...UInt8(ascii: "Z"),
                 UInt8(ascii: "0")...UInt8(ascii: "9"):
                output.append(Character(UnicodeScalar(UInt32(thisChar))!))
            default:
                output = output.appendingFormat("%%%02X", thisChar)
            }
        }
        return output
    }
}
print("https://www.google.es".urlEncoded) //->https%3A%2F%2Fwww.google.es

Some points:

  • You can iterate on each UTF-8 byte with for thisChar in self.utf8

  • To convert a string literal (actually a UnicodeScalar Literal) to a UInt8, you can use UInt8(ascii:)

  • You should better consider using addingPercentEncoding(withAllowedCharacters:) with proper CharacterSet and pre/post-processing

like image 57
OOPer Avatar answered Feb 22 '26 13:02

OOPer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!