xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

SwiftUI encode URL string All In One

SwiftUI encode URL string All In One

Swift encode URL Chinese Unicode

encode URI

黄瓜 => %E9%BB%84%E7%93%9C

const str = `黄瓜`;

encodeURI(str)
// '%E9%BB%84%E7%93%9C'

encodeURIComponent(str)
// '%E9%BB%84%E7%93%9C'

dead code ❌

//
//  OutLinkView.swift
//  Vegetable
//
//  Created by xgqfrms on 2022/5/18.
//

import SwiftUI

struct OutLinkView: View {
  var vegetable: VegetableModel;
  init(_ vegetable: VegetableModel) {
    self.vegetable = vegetable;
  }
  var body: some View {
    GroupBox {
      HStack {
        Text("数据来源")
        Spacer()
        // Link("维基百科", destination: URL(string: "https://zh.wikipedia.org/wiki/\(vegetable.title)")!)
        // Link("维基百科", destination: URL(string: "https://zh.wikipedia.org/wiki/黄瓜")!)
        Link("维基百科", destination: URL(string: "https://zh.wikipedia.org/wiki/%E9%BB%84%E7%93%9C")!)
        Image(systemName: "arrow.up.right.square")
      }
    }
  }
}

struct OutLinkView_Previews: PreviewProvider {
  static var previews: some View {
    OutLinkView(VegetableData[0])
      .previewLayout(.sizeThatFits)
  }
}

solutions ✅

//
//  OutLinkView.swift
//  Vegetable
//
//  Created by xgqfrms on 2022/5/18.
//

import SwiftUI

struct OutLinkView: View {
  var vegetable: VegetableModel;
  init(_ vegetable: VegetableModel) {
    self.vegetable = vegetable;
  }
  func getEncodeURL(_ str: String) -> URL {
    // encode URL with Chinese Unicode
    return URL(string: "https://zh.wikipedia.org/wiki/\(str)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)!;
    // return URL(string: "https://zh.wikipedia.org/wiki/\(str)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!) ?? "https://zh.wikipedia.org/wiki/";
  }
  func getEncodeString(_ str: String) -> String {
    // encode URL with Chinese Unicode
    return str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!;
    // return str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "https://zh.wikipedia.org/wiki/";
    /*
     return str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed);
     Value of optional type 'String?' must be unwrapped to a value of type 'String'
     Coalesce using '??' to provide a default when the optional value contains 'nil'
     Force-unwrap using '!' to abort execution if the optional value contains 'nil'
     */
  }
  var body: some View {
    GroupBox {
      HStack {
        Text("数据来源")
        Spacer()
        Link("维基百科", destination: getEncodeURL(vegetable.title))
        // Link("维基百科", destination: URL(string: getEncodeURL(vegetable.title))
        // Link("维基百科", destination: URL(string: "https://zh.wikipedia.org/wiki/\(vegetable.title)")!)
        // Link("维基百科", destination: URL(string: "https://zh.wikipedia.org/wiki/黄瓜")!)
        // Link("维基百科", destination: URL(string: "https://zh.wikipedia.org/wiki/%E9%BB%84%E7%93%9C")!)
        Image(systemName: "arrow.up.right.square")
      }
    }
  }
}

struct OutLinkView_Previews: PreviewProvider {
  static var previews: some View {
    OutLinkView(VegetableData[0])
      .previewLayout(.sizeThatFits)
  }
}

Online Swift Playground

import Foundation

let domain = "https://zh.wikipedia.org"
let path = "/wiki/黄瓜"

// ❌ change 'let' to 'var' to make it mutable
// let urlcomps = URLComponents(string: domain)!
var urlcomps = URLComponents(string: domain)!
urlcomps.path = path

let url = urlcomps.url!
print("✅ encode unicode URL = \(url)");
// "✅ encode unicode URL = https://zh.wikipedia.org/wiki/%E9%BB%84%E7%93%9C"

// let uri = "https://zh.wikipedia.org/wiki/黄瓜"
// var uricomps = URLComponents(string: uri)!
// let test = uricomps.url!
// print("❌ encode unicode URL = \(test)");
// "Terminated by signal 4"

// "https://zh.wikipedia.org/wiki/黄瓜")
// "https://zh.wikipedia.org/wiki/%E9%BB%84%E7%93%9C"


//
//  OutLinkView.swift
//  Vegetable
//
//  Created by xgqfrms on 2022/5/18.
//

import Foundation

import SwiftUI

struct OutLinkView: View {
  var vegetable: VegetableModel;
  init(_ vegetable: VegetableModel) {
    self.vegetable = vegetable;
  }
  func getEncodeURL(_ str: String) -> URL {
    // encode URL with Chinese Unicode
    return URL(string: "https://zh.wikipedia.org/wiki/\(str)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)!;
    // return URL(string: "https://zh.wikipedia.org/wiki/\(str)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!) ?? "https://zh.wikipedia.org/wiki/";
  }
  func getEncodeURI(_ str: String) -> URL {
    // encode URL with Chinese Unicode
    let domain = "https://zh.wikipedia.org"
    let path = "/wiki/\(str)"
    var urlcomps = URLComponents(string: domain)!
    urlcomps.path = path;
    let url = urlcomps.url!
    print("✅ encode unicode URL = \(url)");
    return url;
    // Cannot convert return expression of type 'URL' to return type 'String'
  }
  func getEncodeString(_ str: String) -> String {
    // encode URL with Chinese Unicode
    return str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!;
    // return str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "https://zh.wikipedia.org/wiki/";
    /*
     return str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed);
     Value of optional type 'String?' must be unwrapped to a value of type 'String'
     Coalesce using '??' to provide a default when the optional value contains 'nil'
     Force-unwrap using '!' to abort execution if the optional value contains 'nil'
     */
  }
  var body: some View {
    GroupBox {
      HStack {
        Text("数据来源")
        Spacer()
        // Link("维基百科-\(vegetable.title)", destination: getEncodeURL(vegetable.title))
        Link("维基百科-\(vegetable.title)", destination: getEncodeURI(vegetable.title))
        // Link("维基百科", destination: URL(string: getEncodeString(vegetable.title) ?? vegetable.title!)
        // ❌ cannot force unwrap value of non-optional type 'String'
        // Link("维基百科", destination: URL(string: "https://zh.wikipedia.org/wiki/\(vegetable.title)")!)
        // Link("维基百科", destination: URL(string: "https://zh.wikipedia.org/wiki/黄瓜")!)
        // Link("维基百科", destination: URL(string: "https://zh.wikipedia.org/wiki/%E9%BB%84%E7%93%9C")!)
        Image(systemName: "arrow.up.right.square")
      }
    }
  }
}

struct OutLinkView_Previews: PreviewProvider {
  static var previews: some View {
    OutLinkView(VegetableData[0])
      .previewLayout(.sizeThatFits)
  }
}

API

func addingPercentEncoding(withAllowedCharacters allowedCharacters: CharacterSet) -> String?

https://developer.apple.com/documentation/foundation/nsstring/1411946-addingpercentencoding

struct URLComponents

https://developer.apple.com/documentation/foundation/urlcomponents

bug

Value of optional type 'URL?' must be unwrapped to a value of type 'URL'

    /*
     Value of optional type 'String?' must be unwrapped to a value of type 'String'
     Coalesce using '??' to provide a default when the optional value contains 'nil'
     Force-unwrap using '!' to abort execution if the optional value contains 'nil'
     */

refs

https://stackoverflow.com/questions/48088342/how-to-get-the-link-if-url-contain-chinese-by-swift

https://stackoverflow.com/questions/24551816/swift-encode-url



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-05-18 14:19  xgqfrms  阅读(224)  评论(3编辑  收藏  举报