본문 바로가기

iOS

[iOS,Swift] URL 인코딩 하기 (PercentEncoding)

String 에서 기본적으로 제공하는 메소드를 사용하여 손쉽게 인코딩을 할수가 있다.

 

let str = "인코딩할 내용";
let encodedStr = str.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

 

withAllowedCharacters 값으로 보통은 urlQueryAllowed 값을 사용하게된다.

 

https://developer.apple.com/documentation/foundation/characterset#2902136

 

CharacterSet | Apple Developer Documentation

A set of Unicode character values for use in search operations.

developer.apple.com

애플 도큐멘트를 보면 항목들이 나오지만 뭐가 인코딩되는지 정확히 알지 못했다.

 

 

아래 설명은 해당 CharacterSet 을 선택하면 나열된 문자를 제외하고 인코딩이 되어진다.

상황에 맞게 골라서 사용하면 되겠다.

 

.urlUserAllowed

! $ & \ ( ) * + , - . ; = _ ~

.urlPasswordAllowed

! $ & \ ( ) * + , - . ; = _ ~

.urlPathAllowed

! $ & \ ( ) * + , - . / : = @ _ ~

.urlHostAllowed

! $ & \ ( ) * + , - . : ; = [ ] _ ~

.urlFragmentAllowed

! $ & \ ( ) * + , - . / : ; = ? @ _ ~

.urlQueryAllowed

! $ & \ ( ) * + , - . / : ; = ? @ _ ~