Swift-URL Extension

获取query参数(扩展属性)

extension URL {
    public var queryParameters: [String: String]? {
        guard let components = URLComponents(url: self,     resolvingAgainstBaseURL: false), let queryItems =   components.queryItems else { return nil }
    
        var items: [String: String] = [:]
    
        for queryItem in queryItems {
            items[queryItem.name] = queryItem.value
        }
    
        return items
    }
}

添加query参数

extension URL {
    public func appendingQueryParameters(_ parameters: [String: String]) -> URL {
        var urlComponents = URLComponents(url: self,    resolvingAgainstBaseURL: true)!
        var items = urlComponents.queryItems ?? []
        items += parameters.map({ URLQueryItem(name: $0,    value: $1) })
        urlComponents.queryItems = items
        return urlComponents.url!
    }
}

添加query参数

extension URL {
    public mutating func appendQueryParameters(_ parameters: [String: String]) {
        self = appendingQueryParameters(parameters)
    }
}

通过key获取query参数的值

extension URL {
    public func queryValue(for key: String) -> String? {
        let stringURL = self.absoluteString
        guard let items = URLComponents(string: stringURL)?.queryItems else { return nil }
        for item in items where item.name == key {
            return item.value
        }
        return nil
    }
}

删除所有的path components返回新的URL

extension URL {
    public func deletingAllPathComponents() -> URL {
        var url: URL = self
        for _ in 0..

删除所有的path components

extension URL {
    public mutating func deleteAllPathComponents() {
        for _ in 0..

获取视频某一刻的缩略图

extension URL {
    public func thumbnail(fromTime time: Float64 = 0) -> UIImage? {
        let imageGenerator = AVAssetImageGenerator(asset: AVAsset(url: self))
        let time = CMTimeMakeWithSeconds(time, 1)
        var actualTime = CMTimeMake(0, 0)
    
        guard let cgImage = try? imageGenerator.copyCGImage(at: time, actualTime: &actualTime) else {
            return nil
        }
        return UIImage(cgImage: cgImage)
    }
}

资源来自网络和日常整理,持续更新

你可能感兴趣的:(Swift-URL Extension)