最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】swift中如何把base的url传入URLComponents

iOS crifan 4368浏览 0评论

折腾:

【已解决】iOS的Swift中如何把JSON字典对象编码为url的query string

后,考虑到生成的字符串是以问号开头的,所以想要支持同时传入base的url,比如此处的:

http://xx.xx.xx.xx/skrDev/src/report/dealer.html

然后根据传入的字典参数:

{

   “t” : 1510906527744,

   “tabId” : “”

}

这样能生成:

http://xx.xx.xx.xx/skrDev/src/report/dealer.html?t=1510899512424&tabId=

所以去搜:

URLComponents swift

URLComponents – Foundation | Apple Developer Documentation

好像是单独的host和path,以及query

-》所以此处要传入的地址,貌似同时包含host和path部分

所以感觉需要造一个URL对象传入才行

Using URLComponents in Swift 3 – Janl Codes – Medium

Swift 3: Using URLComponents

Working With NSURLComponents In Swift – Cocoacasts

【总结】

最后用:

func queryDictToStr(urlBase:String = “”, queryParaDict: [String: Any]) -> String {

    print(“queryDictToStr: urlBase=\(urlBase), queryParaDict=\(queryParaDict)”)

    

    var urlComponents = URLComponents()

    

    if !urlBase.isEmpty {

        if let baseUrl = URL(string: urlBase) {

            if let urlComponentsWithBase = URLComponents(url: baseUrl, resolvingAgainstBaseURL: false) {

                urlComponents = urlComponentsWithBase

//                Printing description of urlComponentsWithBase:

//                ▿ http://xx.xx.xx.xx/skrDev/src/report/dealer.html

//                – scheme : “http”

//                – host : “xx.xx.xx.xx”

//                – path : “/skrDev/src/report/dealer.html”

            }

        }

    }

    print(“url=\(urlBase) -> host=\(urlComponents.host), path=\(urlComponents.path), port=\(urlComponents.port)”)

即可支持输入url后,传入URLComponents

-》可以得到对应的host,path,port等参数了。

-〉后续就可以通过继续转换dict为query para的string了。

-》从而得到最终的url+query string的地址。

完整代码详见:

https://github.com/crifan/crifanLib/blob/master/swift/Http/CrifanLibHttp.swift

转载请注明:在路上 » 【已解决】swift中如何把base的url传入URLComponents

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.167 seconds, using 22.08MB memory