0
let midoriURL = URL(string: "kotoba://dictionary?word=犬")!

I am trying to open a third-party app, Imiwa, and search for a word. If I open that URL in Safari, it will successfully go to the app and open the search result. But trying to make this into a URL in Swift, it is not successfully creating a URL.

alamodey
  • 14,320
  • 24
  • 86
  • 112
  • 1
    `犬` may be causing your issues, it may need to be encoded – MadProgrammer Nov 06 '21 at 06:07
  • I tried to encode the character using `URLComponents`, but it caused a crash. I then tried `"犬".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)` and while this works, it might not produce the result you're after – MadProgrammer Nov 06 '21 at 06:14
  • [This tool](https://cafewebmaster.com/online_tools/rawurlencode) gives the proper encoding of the hiragana character as %E7%8A%AC, so `"kotoba://dictionary?word=%E7%8A%AC"` should work. – Prasun Biswas Nov 06 '21 at 06:21

1 Answers1

0

The URL will only support ASCII characters, unicode characters will need to be encoded.

After a bit of googling and playing around, I was able to get...

var components = URLComponents()
components.scheme = "kotoba"
components.host = "dictionary"
let queryItem = URLQueryItem(name: "word", value: "犬")
components.queryItems = [queryItem]
let url = components.url

to produce Optional(kotoba://dictionary?word=%E7%8A%AC) (you can unwrap it)

(credit to Swift - encode URL)

In my testing I also tried using let escapedString = "犬".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) which also produced "%E7%8A%AC"

I've not tried opening the URL, but at least it's no longer nil

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366