数据
{
"code": 1,
"msg": "操作成功",
"data": {
"url": "https://u.jd.com/q6FopAY",
"short_url": "https://u.jd.com/q6FopAY",
}
}
通过商品短链接跳转京东商品详情页
func goJD(_ url : String){
let jdDict = ["category":"jump", "des":"getCoupon", "url":url ]
guard let jdStr = jdDict.formatJSON() else { return }
let urlStr = "openapp.jdmobile://virtual?params=\(jdStr)"
let utf8Str = urlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
var openSuccess = false
if let jumpURL = URL(string: utf8Str ?? "") {
let isCanOpen = UIApplication.shared.canOpenURL(jumpURL)
if isCanOpen {
UIApplication.shared.open(jumpURL, options: [:], completionHandler: nil)
openSuccess = true
}
}
if (openSuccess == false) {
UIApplication.shared.open(URL(string: url)!, options: [:], completionHandler: nil)
}
}
拓展,Dictionary与JSON字符串相互转换
import Foundation
extension Dictionary {
/// EZSE: Unserialize JSON string into Dictionary
public static func constructFromJSON (json: String) -> Dictionary? {
if let data = (try? JSONSerialization.jsonObject(
with: json.data(using: String.Encoding.utf8,
allowLossyConversion: true)!,
options: JSONSerialization.ReadingOptions.mutableContainers)) as? Dictionary {
return data
} else {
return nil
}
}
/// EZSE: Serialize Dictionary into JSON string
public func formatJSON() -> String? {
if let jsonData = try? JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions()) {
let jsonStr = String(data: jsonData, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
return String(jsonStr ?? "")
}
return nil
}
}