/ MongkeyKing

NSURL 解析

在做MonkeyKing的时候,需要解析NSURL,获取里面的参数,写了个Extension

NSURL Parseer


extension NSURL {
    var prt_URLItems: [String: String]? {

        let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false)
        // 通过 NSURLComponents 获取 URL 的结构


        // queryItems 可以拿到所有参数
        guard let items = components?.queryItems else {
            return nil
        }

        var infos = [String: String]()
        items.forEach {
            //建立字典映射
            infos[$0.name] = $0.value
        }
        return infos
    }
}

用法


let items = NSURL(string: "http://www.weibo.com/1783821582/profile?rightmod=1&wvr=6&mod=personinfo")?.prt_URLItems
print(items)

// Optional(["mod": "personinfo", "rightmod": "1", "wvr": "6"])

NSURL 解析
Share this