gpt4 book ai didi

ios 网址(字符串 : ) not working always

转载 作者:搜寻专家 更新时间:2023-10-30 22:24:50 25 4
gpt4 key购买 nike

let testurl = "http://akns-
images.eonline.com/eol_images/Entire_Site/2018029/rs_1024x759-
180129200032-1024.lupita-nyongo-angela-bassett-black-panther-
premiere.ct.012918.jpg?fit=inside|900:auto"

if let url = URL(string: testurl){
print("valid")
}else {
print("invalid")
}

这将打印为无效的 URL。但在网络浏览器中显示图像。我见过很多方法,但它会抛出 Apple 警告以使用 stringByAddingPercentEncodingWithAllowedCharacters 并且这并不总是有效。

我更喜欢一个解决方案来清理 url 而无需对完整的 urlstring 进行编码。在传递给外部库时,在初始步骤对其进行编码可能会产生摩擦,外部库将重新编码 url 并使其无效。

最佳答案

使用URLComponents,它会自动处理转义字符并正确编码url。无需使用 addingPercentEncoding

func computeURL() {
let testurlStr = "http://akns-images.eonline.com/eol_images/Entire_Site/2018029/rs_1024x759-180129200032-1024.lupita-nyongo-angela-bassett-black-panther-premiere.ct.012918.jpg?fit=inside|900:auto"
let components = transformURLString(testurlStr)

if let url = components?.url {
print("valid")
} else {
print("invalid")
}
}

func transformURLString(_ string: String) -> URLComponents? {
guard let urlPath = string.components(separatedBy: "?").first else {
return nil
}
var components = URLComponents(string: urlPath)
if let queryString = string.components(separatedBy: "?").last {
components?.queryItems = []
let queryItems = queryString.components(separatedBy: "&")
for queryItem in queryItems {
guard let itemName = queryItem.components(separatedBy: "=").first,
let itemValue = queryItem.components(separatedBy: "=").last else {
continue
}
components?.queryItems?.append(URLQueryItem(name: itemName, value: itemValue))
}
}
return components!
}

关于ios 网址(字符串 : ) not working always,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48576329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com