Replace all special characters in String with valid URL characters

I cannot figure out how to replace all special characters in a string and convert it to a string that I can use in the url.

What I use for: I upload an image, converting it to base64, and then passing it to a Laravel structure, however it base64 stringmay contain +, /, \, etc., which changes the value of the URL.

I can replace the character with the +following code:

let withoutPlus = image.stringByReplacingCharactersInRange("+", withString: "%2B")

however, I cannot use this as NSStringto try and change other characters.

Surely there is a way to simply target each individual character and convert it into a usable URL?

+4
source share
3

stringByAddingPercentEncodingWithAllowedCharacters . NSCharacterSet, , (.. , ). NSCharacterSet , URL-, , + /, . , , removeCharactersInString:

let allowedCharacters = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as NSMutableCharacterSet
allowedCharacters.removeCharactersInString("+/=")

stringByAddingPercentEncodingWithAllowedCharacters , allowedCharacters:

let encodedImage = image.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters)

, String (String?), , , :

if let encodedImage = image.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters) {
    /* use encodedImage here */
} else {
    /* stringByAddingPercentEncodingWithAllowedCharacters failed for some reason */
}

:

let unencodedString = "abcdef/+\\/ghi"

let allowedCharacters = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as NSMutableCharacterSet
allowedCharacters.removeCharactersInString("+/=")

if let encodedString = unencodedString.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters) {
    println(encodedString)
}

ABCDEF% 2F% 2B% 5C% 2Fghi

+5

let withoutPlus = image.stringByReplacingOccurrencesOfString("+", withString: "%2B")

image.stringByReplacingCharactersInRange. , ,

func stringByReplacingCharactersInRange(range: Range<String.Index>, withString replacement: String) -> String 

.

0

You might be better off using POST to send the file rather than encoding it in your URL

0
source

All Articles