使用 Swift for iOS 执行深度链接后不应显示百分比编码

问题描述 投票:0回答:1

我有以下字符串(请注意字符串中有“&”)

let text = "By submitting, I confirm that I am an American, above 18 yrs of age & residing in America. I have read & agree to American Bank. I also agree to receive calls, SMS & WhatsApp messages from American Bank"

这就是我对字符串进行编码的方式:

let encodedTxt = text.removingPercentEncoding?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""

为了工作示例,我将将此字符串发送到 Bear 应用程序。这就是我创建深层链接 URL 的方法:

var components = URLComponents(string: "bear://x-callback-url/create")!
            components.queryItems = [
                URLQueryItem(name: "title", value: "Title),
                URLQueryItem(name: "text", value: encodedTxt),
                URLQueryItem(name: "x-success", value: "myapp://bear-note-created")
            ]

这是 url 组件的输出

bear://x-callback-url/create?title=\(title)&text=\(encodedTxt)&x-success=myapp://bear-note-created

当执行上面的链接时,我看到输出仍然有小熊应用程序中的编码

By%20submitting,%20I%20confirm%20that%20I%20am%20an%20American,%20above%2018%20yrs%20of%20age%20&%20residing%20in%20America.%20I%20have%20read%20&%20agree%20to%20American%20Bank%20Privacy%20Policy.%20I%20also%20agree%20to%20receive%20calls,%20SMS%20&%20WhatsApp%20messages%20from%20American%20Bank

预期结果在输出中必须没有百分比编码。

非常感谢任何帮助。

ios swift url deep-linking urlencode
1个回答
0
投票

我已将您的代码片段变成了工作测试,并减小了文本大小以使其更具可读性。

import Foundation

let text = "age & residing"
let encodedTxt = text.removingPercentEncoding?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
print(encodedTxt)

var components = URLComponents(string: "bear://x-callback-url/create")!
components.queryItems = [
                URLQueryItem(name: "title", value: "Title"),
                URLQueryItem(name: "text", value: encodedTxt),
                URLQueryItem(name: "x-success", value: "myapp://bear-note-created")
            ]
print("\n1 Components:")
print(components.string!)

components.queryItems = [
                URLQueryItem(name: "title", value: "Title"),
                URLQueryItem(name: "text", value: text),
                URLQueryItem(name: "x-success", value: "myapp://bear-note-created")
            ]
print("\n2 Components:")
print(components.string!)

这是我得到的输出:

age%20&%20residing

1 Components:
bear://x-callback-url/create?title=Title&text=age%2520%26%2520residing&x-success=myapp://bear-note-created

2 Components:
bear://x-callback-url/create?title=Title&text=age%20%26%20residing&x-success=myapp://bear-note-created

您的编码对空格进行编码,但由于

&
而省略了
.urlQueryAllowed
。然后,创建
URLQueryItem
会进行第二次编码,但不会省略
&
1 Components:
下面的行)。最需要注意的是,所有
%
符号已更改为
%25
,如果您想在字符串中使用文字
%
,这是正确的百分比编码。

接收 URL 的应用程序将对查询进行 one 百分比解码。它将把

%25
解码为
%
,并将
%26
解码为
&
。这些是它将看到的唯一百分比编码字符。此时,它无法识别百分比编码空格,因为它看起来像一个百分比编码的
%
,后面有文字数字 20。

如果您正在使用

URLQueryItem
您根本不需要自己进行百分比编码。只需输入未编码的字符串即可。这可以从上面
queryItems
的第二个赋值中看出。输出(下方
2 Components:
)正是您将字符串作为查询项传输所需的内容。

© www.soinside.com 2019 - 2024. All rights reserved.