iOS基础之URLComponents

2017-10-16  本文已影响506人  flionel
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)")
    }
}
上一篇下一篇

猜你喜欢

热点阅读