美文网首页
iOS基础之URLComponents

iOS基础之URLComponents

作者: flionel | 来源:发表于2017-10-16 16:40 被阅读506次
    playground.jpeg

    创建URL的方法

    var url = URL(string: "https://myapi.com")
    print(url)
    url?.appendPathComponent("users")
    print(url)
    

    // 这样创建存在一些问题

    介绍URLComponents

    var components = URLComponents()
    components.scheme = "https"
    components.host = "myapi.com"
    print(components.url)
    
    let queryItemToken = URLQueryItem(name: "token", value: "API.TOKEN")
    let queryItemQuery = URLQueryItem(name: "query", value: "swift iOS")
    components.queryItems = [queryItemToken, queryItemQuery]
    print(components.url)
    
    let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    
    extension String
        {   
            func encodeUrl() -> String
            {
                return self.addingPercentEncoding( withAllowedCharacters: NSCharacterSet.urlQueryAllowed())
            }
        func decodeUrl() -> String
            {
                return self.removingPercentEncoding
            }
    
        }
    
    components.fragment = "five"
    components.user = "bartjacobs"
    components.password = "mypassword"
    print(components.url)
    print(components.query)
    

    获取url和query内容

    print(components.host)
    print(components.percentEncodedQuery)
    if let queryItems = components.queryItems {
        for queryItem in queryItems {
            print("\(queryItem.name): \(queryItem.value)")
        }
    }
    

    相关文章

      网友评论

          本文标题:iOS基础之URLComponents

          本文链接:https://www.haomeiwen.com/subject/iixluxtx.html