관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] URL encoding (addingPercentEncoding) 개념, (URL 인코딩 nil, 한글 인코딩, 띄어쓰기 인코딩) 본문

iOS 응용 (swift)

[iOS - swift] URL encoding (addingPercentEncoding) 개념, (URL 인코딩 nil, 한글 인코딩, 띄어쓰기 인코딩)

jake-kim 2022. 2. 17. 23:14

addingPercentEncoding 개념

  • 일반적인 인코딩을 시도할 때 내부적으로 지정된 Set을 참고하여 인코딩하지만, Set에 없는 문자 (한글, 띄어쓰기)와 같은 것들을 %인코딩된 문자로 인코딩 시도

https://developer.apple.com/documentation/foundation/nsstring/1411946-addingpercentencoding

  • String to URL 인코딩 시, 한글이 있어서 nil리턴
let someURLString = "https://ios-development.tistory.com/search?keyword=최신기술"
let url = URL(string: someURLString)
print(url) // nil

인코딩할때 애플에서 정의한 Set 종류

  • CharacterSet에 정의된 문자들은 encoding되는게 아닌 키워드로 인식하라는 의미

인코딩 시 Set 선택

  • urlQueryAllowed
    ! $ & \ ( ) * +  - . / : ; = ? @ _ ~
  • urlPathAllowed
    ! $ & \ ( ) * +  - . / : = @ _ ~​

-> 보통 urlQueryAllowed를 사용 (query parameter에는 url string에 '?'가 들어가기 때문에 이것은 키워드로 인식시키기 위함)

 

addingPercentEconding과 urlQueryAllowed 사용하여 시도

  • 한글이 있는 url string을 percent encdoing으로 string 변경
    let someURLString = "https://ios-development.tistory.com/search?keyword=최신기술"
    let result = someURLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    print(result) // Optional("https://ios-development.tistory.com/search?keyword=%EC%B5%9C%EC%8B%A0%EA%B8%B0%EC%88%A0")​
  • URL 인코딩
    let url = URL(string: result!)
    print(url) // https://ios-development.tistory.com/search?keyword=%EC%B5%9C%EC%8B%A0%EA%B8%B0%EC%88%A0​

* 참고

https://developer.apple.com/documentation/foundation/nsstring/1411946-addingpercentencoding

https://dongminyoon.tistory.com/64

Comments