URLQueryItems

时间:2016-12-22 00:18:20

标签: swift string special-characters deep-linking firebase-dynamic-links

我需要在我的应用中创建firebase深层链接,以便使用UIActivityViewController在不同平台上共享它们。 为了创建这些链接,我使用以下代码与URLQueryItem获取我将分享给其他应用程序的URL:

func createURLWithComponents(EventToUrl: Event) -> URL? {

    var urlComponents = URLComponents()
    urlComponents.scheme = "https"
    urlComponents.host = "www.example.com"
    urlComponents.path = "/"

    // add params
    let id = URLQueryItem(name: "id", value: EventToUrl.eventID)

    print(EventToUrl.name)
    let name = URLQueryItem(name: "name", value: EventToUrl.name)
    print(name.description)
    print(name.value)
    let photo = URLQueryItem(name: "photo", value:  EventToUrl.photoUrl)
    let created = URLQueryItem(name: "created", value: EventToUrl.creationDate )
    let participants = URLQueryItem(name: "participants", value: String(EventToUrl.Participants.count) )
    let place = URLQueryItem(name: "place", value: EventToUrl.Places[0].name)
    let time = URLQueryItem(name: "time", value: EventToUrl.time[0].TimestampString)
    urlComponents.queryItems = [id, name, photo, created, participants , place , time]

    let dynamicLinkDomain : String = "***.app.goo.gl"
    var deepLink = URLComponents()
    deepLink.scheme = "https"
    deepLink.host = dynamicLinkDomain
    deepLink.path = "/"

    let link = URLQueryItem(name: "link", value:  urlComponents.url?.absoluteString)
    let apn = URLQueryItem(name: "apn", value: "***" )
    let ibi = URLQueryItem(name: "ibi", value: "***" )
    let d = URLQueryItem(name: "d", value: "1")
    deepLink.queryItems = [link, apn, ibi, d]
    print(deepLink.url?.absoluteString)
    print(deepLink.url)

    return deepLink.url
}

这是我发送给他时的链接:

https://***.app.goo.gl/?link=https://www.example.com/?id%3D-KZYfNRCXdSqUG72FmEQ%26name%3Djeremie's%2520Event%26photo%3D%26created%3D%26participants%3D1%26place%3DLa%2520Piazza%26time%3D1482362284.50304&apn=***&ibi=***&d=1

的https:// .app.goo.gl /链接= https://www.example.com/?id%3D-KZYfNRCXdSqUG72FmEQ%26name%3Djeremie' S%2520Event%26photo%3D%26created%3D%26participants%3D1%26place% 3DLa%2520Piazza%26time%3D1482362284.50304&安培; APN = &安培; IBI = ***&安培; d = 1

如你所见'如果事件名称由"组成' "角色(Jeremie的事件),URLQueryItem没有正确编码这个角色(在我的Android应用程序中,系统函数将其转换为"'" - >%27 ) 我该如何编码? PS:我尝试addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)没有成功...... 谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

我找到了一个比其他解决方案更简单的解决方案。 (至少对我而言)

我正常构建了我的URLComponents,但在从它获取url之前,我获取了urlComponents.string并用符号替换了特殊代码。我通过添加PercentEncoding运行该字符串,然后从该字符串中创建一个url。

let stringWithoutBS = urlComponents.string!.replacingOccurrences(of: "%27", with: "'")
        //ignore the force unwrap

guard let encodedURL = stringWithoutBS.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else {
            print("unhelpful message")
            return nil
        }

var correctURL = URL(string: encodedURL)