URL encounter Chinese characters could not be initialized

In the Swift,We often used to initialize a URL path,For example, links to web pages。For example, this:

When the user clicks the button (for example, the Help button),Then all of a sudden will help the user to open the default browser,And opens the specified page (here's a forum)。

Then,If this is your link: "https://How gracefully v2mm.tech/topic/618/ use pocketed input method dashed function" Then it is unfortunate,collapse。

The reason is the collapse of NSWorkspace.shared.open(url!) This is a,Another point that is specific url This variable encountered a null value - that white is a null pointer。Why is this so?

Obviously,The URL object is not successful initialization。

URL can not handle Chinese characters

We must use some other way to make him Initialization - after all,Browser support such a link open,You can not go to the site requires providers to change their pages link,This time is necessary to use % Dafa。

Percent-encoding

Is often said that the percent-encoding,It allows URL ,That is your link to support some weird characters - such as Chinese。So,Above us that string,It may be so: https://v2mm.tech/topic/618/%D4%F5%D1%F9%D3%C5%D1%C5%B5%D8%CA%B9%D3%C3%C2%E4%B8%F1%CA%E4%C8%EB%B7%A8%B5%C4%B5%E3%BB%AE%B9%A6 The above link and are equivalent with Chinese。In fact,Occasionally you will see a long list of the percent jump in the number of web pages,In fact, they just put the link to jump to become the percent complete coding format,Including those ///https%3A%2F%2Fv2mm.tech%2Ftopic%2F618%2F%D4%F5%D1%F9%D3%C5%D1%C5%B5%D8%THAT%B9%D3%C3%C2%E4%B8%F1%THAT%E4%C8%EB%B7%A8%B5%C4%B5%E3%BB%AE%B9%A6%C4%DC

Thus,This turned into the URL text string does not make sense,To avoid ambiguity when mass participation in the URL path in。

Then

How to use the code to implement this coding it?

The API can use ready-made,as follows:

But you have to pay attention,Such coding,Entire string will be encoded,So we only need to encode Chinese section,So specific examples herein,That's it:

Further reading

https://zh.wikipedia.org/zh-cn/百分号编码

http://web.chacuo.net/charseturlencode

Published by R0uter

The non-declaration,I have written articles are original,Reproduced, please indicate the link on this page and my name。

Join the Conversation

2 Comments

Your email address will not be published. Required fields are marked *