0

I attempt to create URL from components

var com =  URLComponents()
com.scheme = "http"
com.host = "192.168.1.99"
com.port = 77
com.path = "/api/dosomething/55"

print("SHOW ME URl =  \(com.url!))")

What I got is something like this

http://192.168.1.99:77/%EF%BB%BFapi/dosomething/55

Always got %EF%BB%BF, in which case the url becomes invalid

I want to remove %EF%BB%BFfrom the URL

How can I do that?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Nekkoko Nabby
  • 57
  • 2
  • 6
  • I can't, reproduce, when I copy-pasted your code, I got `SHOW ME URl = http://192.168.1.99:77/api/dosomething/55)`/ Tested in Playground, Xcode 10. – regina_fallangi Oct 05 '18 at 09:59
  • 4
    `%EF%BB%BF` is an percent encoded byte sequence of ZERO WIDTH NON-BREAKING SPACE(aka BOM in UTF-16/UTF-32). In UTF-8, it's just an extra character. You may be taking the path component from some external resource. You may need to fix that part or the way creating the external resource. – OOPer Oct 05 '18 at 10:01
  • For example, some Japanese-made editors show `UTF-8 with extra ZERO WIDTH NON-BREAKING SPACE` as **UTF-8**, and the right `UTF-8` as **UTF-8N**. You need to use the right `UTF-8`. – OOPer Oct 05 '18 at 10:04

3 Answers3

0

Direct answer to your question

You can replace this pattern with nothing :

let theURL = "http://192.168.1.99:77/%EF%BB%BFapi/dosomething/55"
let partToRemove = "%EF%BB%BF"
let clearURL = theURL.replacingOccurrences(of: partToRemove, with: "")
print(clearURL)
Essam Fahmi
  • 1,920
  • 24
  • 31
0

That's a URL-encoding of a UTF-8 BOM, it may be caused by processing of the URLs with some text editors. Trim white spaces from your path string:

var com =  URLComponents()
com.scheme = "http"
com.host = "192.168.1.99"
com.port = 77
let path = //The path
let trimmedPath = path.trimmingCharacters(in: .whitespaces)
com.path = trimmedPath

print("SHOW ME URl =  \(com.url!)")

In utf-8, the 'ZERO WIDTH NO-BREAK SPACE' is encoded as 0xEF 0xBB 0xBF

ielyamani
  • 17,807
  • 10
  • 55
  • 90
0

In complement to ielyamani's answer, as .whitespaces does not seem to contain the BOM character, I suggest this :

extension String
{
    var withoutBom: String
    {
        let bom = "\u{FEFF}"
        if self.starts(with: bom)
        {
            return String(dropFirst(bom.count))
        }
        return self
    }
}

and then using something like :

path.withoutBom
Pierre
  • 422
  • 2
  • 12