반응형
// 사용 방법
let url = URL(string:"https://www.test.com/myconmand?param1=ASDF¶m2=1234")!
let qParams = url.queryParams().toJsonString()
let param2 = url.valueOf("param2")
print(
"""
scheme = \(url.scheme ?? "")
host = \(url.host ?? "")
path = \(url.path)
query = \(url.query ?? "")
qParams = \(qParams)
param2 = \(param2 ?? "")
"""
)
// 결과
scheme = https
host = www.test.com
path = /myconmand
query = param1=ASDF¶m2=1234
qParams = {"param1":"ASDF","param2":"1234"}
param2 = 1234
extension URL {
func queryParams() -> [String:Any] {
let queryItems = URLComponents(url: self, resolvingAgainstBaseURL: false)?.queryItems
let queryTuples: [(String, Any)] = queryItems?.compactMap{
guard let value = $0.value else { return nil }
return ($0.name, value)
} ?? []
return Dictionary(uniqueKeysWithValues: queryTuples)
}
func valueOf(_ queryParamaterName: String) -> String? {
guard let url = URLComponents(string: self.absoluteString) else { return nil }
return url.queryItems?.first(where: { $0.name == queryParamaterName })?.value
}
}
extension Dictionary {
func toJsonData() -> Data {
var jsonData: Data?
do {
jsonData = try JSONSerialization.data(withJSONObject: self, options: .init(rawValue: 0))
} catch {
print(error)
}
return jsonData!
}
func toJsonDataPrettyPrinted() -> Data {
var jsonData: Data?
do {
jsonData = try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions.prettyPrinted)
} catch {
print(error)
}
return jsonData!
}
func toJsonString() -> String {
return toJsonData().toString()
}
func toPrettyPrintedJsonString() -> String {
return toJsonDataPrettyPrinted().toString()
}
}
extension Data {
func hexString() -> String {
return map { String(format: "%02hhx", $0) }.joined()
}
func toString() -> String {
return String(data: self, encoding: String.Encoding.utf8)!
}
}
2020/12/16 - [개발노트] - Code 128 Barcode의 Check Digit 계산방법
2020/12/15 - [iOS/Tips] - 디버깅 차단 처리 (Anti Debug)
2020/12/14 - [iOS/Tips] - bundle id 알아내기
2020/12/12 - [AI/Algorithm] - 2D 충돌처리
2020/12/11 - [iOS/Swift] - UIViewController 스위칭
2020/12/11 - [개발노트] - PlantUML 설치 (Mac OS X)
2020/12/10 - [iOS/Objective-C] - 웹뷰에서 javascript 함수 동기식 호출
2020/12/10 - [iOS/Tips] - Fat Static Library 빌드 (2/2)
2020/12/10 - [iOS/Tips] - Fat Static Library 빌드 (1/2)
2020/12/10 - [iOS/Tips] - Custom UserAgent 설정
2020/12/10 - [iOS/Tips] - CocoaPods 설치 및 제거
2020/12/10 - [iOS/Tips] - Clang diagnostic 경고 무시하기
반응형
'개발 > iOS' 카테고리의 다른 글
SceneDelegate 포인터 구하기 (0) | 2021.01.05 |
---|---|
앱 호출 (URL scheme) (0) | 2021.01.05 |
디버깅 차단 처리 (Anti Debug) (0) | 2020.12.15 |
bundle id 알아내기 (0) | 2020.12.14 |
UIViewController 스위칭 (0) | 2020.12.11 |