Swift 中级100问系列之 85 swift网络编程如何从URL中提取组件(中文教程含解决方案)

实战需求

swift网络编程如何从URL中提取组件


解决方案

import Foundation
let url = "http://mydomain.com/test/blog/index.php?q=1&show=true"
//Then, we extract the components.
if let components = URLComponents(string: url) {
    // Let's retrieve them one by one
    let scheme = components.scheme
    let host = components.host
    let path = components.path
    let query = components.query
    // And print them out
    // Note: .scheme, .host, and .query return optionals,
    // but in this particular case, it's rather safe to force-unwrap them
    print("Scheme: \(scheme!)")
    print("Host: \(host!)")
    print("Path: \(path)")
    print("Query: \(query!)")
}

//SwiftUI技术交流QQ群:518696470
Scheme: http
Host: mydomain.com
Path: /test/blog/index.php
Query: q=1&show=true
QQ:3365059189

加入我们一起学习SwiftUI

QQ:3365059189
SwiftUI技术交流QQ群:518696470
教程网站:www.openswiftui.com

发表回复