美文网首页Swift
Swift-URL Extension

Swift-URL Extension

作者: 长风浮云 | 来源:发表于2018-05-15 11:36 被阅读0次

    获取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..<pathComponents.count - 1 {
                url.deleteLastPathComponent()
            }
            return url
        }
    }
    

    删除所有的path components

    extension URL {
        public mutating func deleteAllPathComponents() {
            for _ in 0..<pathComponents.count - 1 {
               deleteLastPathComponent()
              }
        }
    }
    

    获取视频某一刻的缩略图

    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

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