URL constructor doesn't work with some characters

◇◆丶佛笑我妖孽 提交于 2021-02-05 10:44:10

问题


I'm trying to call a php-script from my app using URLRequest. The Url path is generated in the String-Variable query and for the request I convert it like this

    guard let url = URL(string: query) else {
        print("error")
        return
    }

usually it works, but when the request contains characters like ä, ö, ü, ß the error is triggered. How can I make it work?


回答1:


The URL(string:) initializer doesn't take care of encoding the String to be a valid URL String, it assumes that the String is already encoded to only contain characters that are valid in a URL. Hence, you have to do the encoding if your String contains non-valid URL characters. You can achieve this by calling String.addingPercentEncoding(withAllowedCharacters:).

let unencodedUrlString = "áűáeqw"
guard let encodedUrlString = unencodedUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: encodedUrlString) else { return }

You can change the CharacterSet depending on what part of your URL contains the characters that need encoding, I just used urlQueryAllowed for presentation purposes.




回答2:


Split your URL in two separate parts:

let baseURLString = "https://www.example.com"
let pathComponent = "áűáeqw"
let fullURL = URL(string: baseURLString)?.appendingPathComponent(pathComponent)


来源:https://stackoverflow.com/questions/50466880/url-constructor-doesnt-work-with-some-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!