Swift 인코딩 옵션

|

한글인코딩 처리

인코딩 처리 옵션이 엄청나게 많은데 일단 한글은 다음처럼 .urlQueryAllowed를 사용하자.

출처: https://m.blog.naver.com/itperson/220860433667

func makeStringKoreanEncoded(_ string: String) -> String {
    return string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? string
}

Query Allowed 옵션에 대한 표는 다음과 같다.

key chars example
urlFragmentAllowed !$&’()*+,-./:;=?@_~ http://google.com?a=b&c=d
urlHostAllowed !$&’()*+,-.:;=[]_~ http:%2F%2Fgoogle.com%3Fa=b&c=d
urlPathAllowed !$&’()*+,-./:=@_~ http://google.com%3Fa=b&c=d
urlQueryAllowed !$&’()*+,-./:;=?@_~ http://google.com?a=b&c=d
urlUserAllowed !$&’()*+,-.;=_~ http%3A%2F%2Fgoogle.com%3Fa=b&c=d
urlPathAllowed !$&’()*+,-./:=@_~ http://google.com%3Fa=b&c=d

출처:

http://slee2540.tistory.com/?page=2

RFC3986을 따르는 경우

아래

RFC 3986의 섹션 2.3에 의하면 아래 문자들은 인코딩 하면 안 됨. 보다시피 틸드(tilde)를 인코딩해서는 안된다.

ALPHA
DIGIT
“-”
“.”
“_”
“~”

더불어 query 는 /와 ? 문자또한 인코딩해서는 안된다. 이는 Alamofire 등에 구현된 내용이기도 함.

주의: 아래 코드는 SWIFT2 이므로 변환필요

extension String {
  func stringByAddingPercentEncodingForRFC3986() -> String? {
    let unreserved = "-._~/?"
    let allowed = NSMutableCharacterSet.alphanumericCharacterSet()
    allowed.addCharactersInString(unreserved)
    return stringByAddingPercentEncodingWithAllowedCharacters(allowed)
  }
}

// 사용
let query = "one&two =three"
let encoded = query.stringByAddingPercentEncodingForRFC3986()
// "one%26two%20%3Dthree"

x-www-form-urlencoded 를 따르는 경우

W3C HTML5 가 권장하는 인코딩 폼 데이터는 RFC 3986와 살짝 다르다. Section 4.10.22.5에 따르면 다음 문자에 대해 인코딩을 하면 안 된다. RFC 3986의 경우 별표( *)를 인코딩하지만 여기서는 그 반이며 틸트(~)의 경우에 RFC 3986는 인코딩제외목록에 있지만 여기서는 그 반대다. 사실 아주 혼동스러움 그 자체이다!!!

ALPHA DIGIT “*” “-” “.” “_”

코드는 위의 것 보다 조금 더 복잡하다.

public func stringByAddingPercentEncodingForFormData(plusForSpace: Bool=false) -> String? {
    let unreserved = "*-._"
     var allowed = CharacterSet.alphanumerics
    allowed.insert(charactersIn: unreserved)
    if plusForSpace {
        allowed.insert(charactersIn: " ")
    }

    var encoded = self.addingPercentEncoding(withAllowedCharacters: allowed)
    if plusForSpace {
         encoded =  encoded?.replacingOccurrences(of: " ", with: "+")
    }
    return encoded
}

// 사용
let query = "one two"
let space = query.stringByAddingPercentEncodingForFormData()
// "one%20two"
// 기본 옵션으로 하면 공백 --> %20으로 인코딩 한다.

let plus = query.stringByAddingPercentEncodingForFormData(true)
// "one+two"

출처: https://useyourloaf.com/blog/how-to-percent-encode-a-url-string/

Query와 URL방식으로 인코딩 할 때

참고: https://code.i-harness.com/ko-kr/q/176a188

let originalString = "http://www.ihtc.cc?name=htc&title=iOS开发工程师"

1. encodingQuery :

let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)

결과:

"http://www.ihtc.cc?name=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88" 

2. encodingURL :

let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

결과:

"http:%2F%2Fwww.ihtc.cc%3Fname=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88"

이미지URL경로에 한글이 포함될 때

여기부터 내용은 모두 발췌한 것이다.

Kingfisher는 이미지 캐싱 라이브러리이다.

example.swift

let url = URL(string: "url_of_your_image")
imageView.kf.setImage(with: url)

이슈: Kingfisher에서 요청 할 때 url에 한국어가 포함되어 있을 때

url에 한국어가 포함된 경우 addingPercentEncoding을 이용하면 된다.

example.swift

// 원하는 urlString을 addingPercentEncoding을 통해 바꿔줍니다.
let urlString = urlString?.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)

// 그 후 원하는 ImageView에 적용시키시면 됩니다.
imageView.kf.setImage(with: URL(string: urlString), placeholder: defaultImg, options: [.transition(ImageTransition.fade(0.5))])

출처: (https://twpower.github.io/tags#Swift)

기타사항(toRead)

URLComponets에 대한 글

https://cocoacasts.com/working-with-nsurlcomponents-in-swift

==> 아직 읽어보지 못함.

UNICODE에 대한 링크

https://en.wikipedia.org/wiki/Percent-encoding

캐릭터셋 참고: https://www.degraeve.com/reference/urlencoding.php

URL 인코딩된 캐릭터

      backspace      %08
      tab            %09
      linefeed       %0A
      creturn        %0D
      space          %20
      !              %21
      "              %22
      #              %23
      $              %24
      %              %25
      &              %26
      '              %27
      (              %28
      )              %29
      *              %2A
      +              %2B
      ,              %2C
      -              %2D
      .              %2E
      /              %2F
      0              %30
      1              %31
      2              %32
      3              %33
      4              %34
      5              %35
      6              %36
      7              %37
      8              %38
      9              %39
      :              %3A
      ;              %3B
      <              %3C
      =              %3D
      >              %3E
      ?              %3F
      @              %40
      A              %41
      B              %42
      C              %43
      D              %44
      E              %45
      F              %46
      G              %47
      H              %48
      I              %49
      J              %4A
      K              %4B
      L              %4C
      M              %4D
      N              %4E
      O              %4F
      P              %50
      Q              %51
      R              %52
      S              %53
      T              %54
      U              %55
      V              %56
      W              %57
      X              %58
      Y              %59
      Z              %5A
      [              %5B
      \              %5C
      ]              %5D
      ^              %5E
      _              %5F
      `              %60
      a              %61
      b              %62
      c              %63
      d              %64
      e              %65
      f              %66
      g              %67
      h              %68
      i              %69
      j              %6A
      k              %6B
      l              %6C
      m              %6D
      n              %6E
      o              %6F
      p              %70
      q              %71
      r              %72
      s              %73
      t              %74
      u              %75
      v              %76
      w              %77
      x              %78
      y              %79
      z              %7A
      {              %7B
      |              %7C
      }              %7D
      ~              %7E
      ¢              %A2
      £              %A3
      ¥              %A5
      |              %A6
      §              %A7
      «              %AB
      ¬              %AC
      ¯              %AD
      º              %B0
      ±              %B1
      ª              %B2
      ,              %B4
      µ              %B5
      »              %BB
      ¼              %BC
      ½              %BD
      ¿              %BF
      À              %C0
      Á              %C1
      Â              %C2
      Ã              %C3
      Ä              %C4
      Å              %C5
      Æ              %C6
      Ç              %C7
      È              %C8
      É              %C9
      Ê              %CA
      Ë              %CB
      Ì              %CC
      Í              %CD
      Î              %CE
      Ï              %CF
      Ð              %D0
      Ñ              %D1
      Ò              %D2
      Ó              %D3
      Ô              %D4
      Õ              %D5
      Ö              %D6
      Ø              %D8
      Ù              %D9
      Ú              %DA
      Û              %DB
      Ü              %DC
      Ý              %DD
      Þ              %DE
      ß              %DF
      à              %E0
      á              %E1
      â              %E2
      ã              %E3
      ä              %E4
      å              %E5
      æ              %E6
      ç              %E7
      è              %E8
      é              %E9
      ê              %EA
      ë              %EB
      ì              %EC
      í              %ED
      î              %EE
      ï              %EF
      ð              %F0
      ñ              %F1
      ò              %F2
      ó              %F3
      ô              %F4
      õ              %F5
      ö              %F6
      ÷              %F7
      ø              %F8
      ù              %F9
      ú              %FA
      û              %FB
      ü              %FC
      ý              %FD
      þ              %FE
      ÿ              %FF

Swift 에러 처리 (번역 요약)

|

출처) https://www.swiftbysundell.com/posts/picking-the-right-way-of-failing-in-swift 등급) 2/5 의견) 좀 더 깊은 설명과 예제가 필요함. 배운점) assert는 릴리즈 빌드에서 작동하지 않는다.

Swift 에러 처리에 대한 블로그 글을 매우 간단하게 요약했으므로 원문과 예제를 보려면 출처 사이트를 참고하자.

에러 처리에 관한 메소드

  • assert()
  • precondition()
  • fatalError()
  • exit()

각 메소드의 차이점

  • nil 또는 error enum case 를 반환. 가장 간단한 형태이다. 많은 상황에서 유용하지만 적당히 사용해야 한다.
  • Throwing an error (using throw MyError), 호출한 측(caller)에서 에러 처리를 해야 하는 경우이며 do, try, catch 패턴을 사용한다. 또 다른 방법으로 에러를 무시하려면 호출 측에서 try?를 사용한다.
  • assert() , assertionFailure() 특정 조건이 true인지 검증할 때 사용함. DEBUG빌드에서 이 메소드는 Crash를 발생시키지만, RELEASE 빌드에서는 무시된다. 일종의 런타임 강력 경고로 보자.
  • precondition() , preconditionFailure() assert()와의 가장 큰 차이는 DEBUG , RELEASE 빌드 모두에서 검증(evaluated) 된다는 점이다. 따라서 조건을 만족하지 못하면 절대로 다음 루틴이 진행되지 않는다.
  • fatalError()  호출 즉시 프로세스를 죽인다. 즉 크래시 발생한다.
  • exit() 프로세스를 종료시킨다.

에러처리 분류

복구 가능한 종류(Recoverable)

  • nil 또는 error enum case 를 반환
  • throwing an error

복구 불능한 종류(Non-recoverable)

  • assert()
  • precondition()
  • fatalError()
  • exit()

프로그래머의 실수 vs 실행 오류 (execution errors)

  1. 프로그래머의 실수(잘못된 로직이나 config의 오류)
    • 복구 불가능 옵션을 사용하자
    • 유닛테스팅
  2. 외부 요인에 의한 오류

git 에러 발생처리. REMOTE Url연결

|

이슈: 이미 remote 가 연결되어 있다는 에러가 발생하면~

Github “fatal: remote origin already exists”

해결: 새로운 remote url을 설정함.

현재 설정된 URL을 보고 변경하거나, 삭제하고 새로 url을 추가해줌.

  • 현재 설정된 리모트 URL보기
    $ git config --get remote.origin.url https://github.com/someUser/xxx.git
    

    또는

    $ git remote get-url origin
    

또는 어디에 연결되었나 볼때는 다음처럼 한다.

$ git remote -v
origin	https://github.com/xxx/yyyy.git (fetch)
origin	https://github.com/xxx/yyyy.git (push)
  • 리모트 추가하기 ( 리모트 URL이 없을때)
    $ git remote add origin https://github.com/someUser/xxx.git
    
  • 리모트 URL 갱신 이미 리모트 주소가 있다면 fatal: remote origin already exists. 가 발생함. 이때는 기존 주소를 삭제후 다시 add 하면 됨.
    $ git remote rm origin
    $ git remote add origin https://github.com/someUser/xxx.git
    

이슈: github에 잘못된 ID로 계속 나타남.

증상: 로컬에서 eddie로 커밋하고, push했으나, github에 확인해보면 “hallomuzexxx Initial Commit” 이라고 나옴

증상

해결: 정확히는 모르겠으나 global email을 변경하고 나서 괜찮아짐.

아래처럼 여러가지 시도후에 해결되었으나 정확히 어떻게 해결된 것인지는 모르겠음. @.@

의심 1: global email변경 ( email = hallomuzexxx@gmail.com를 eddiexxx@gmail로 변경했음. )

git config --global user.email "eddiexxx@gmail.com"

의심 2: xcode자체 이슈 ( 사실 xcode 가 아닌 terminal 에서 touch로 파일생성하면 문제가 없음.) 의심 3:

  • 유저명 변경
    git config --global user.name "Jessica Lisa"
    git config --local user.name "Jessica Lisa"
    

시스템영역의 git config 읽어보기

 cat ~/.gitconfig

결과

[core]
	excludesfile = /Users/eddiek/.gitignore_global
	precomposeunicode = true
	quotepath = false
[difftool "sourcetree"]
	cmd = opendiff \"$LOCAL\" \"$REMOTE\"
	path =
[mergetool "sourcetree"]
	cmd = /Applications/Sourcetree.app/Contents/Resources/opendiff-w.sh \"$LOCAL\" \"$REMOTE\" -ancestor \"$BASE\" -merge \"$MERGED\"
	trustExitCode = true
[user]
	name = eddiekwon
	email = hallomuzexxx@gmail.com
[commit]
	template = /Users/eddiek/.stCommitMsg
[alias]
  tre = log --graph --decorate --pretty=oneline --abbrev-commit --all --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)'

  lg1 = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all
  lg2 = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n''          %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all
  lg = !"git lg1"

[mergetool "Kaleidoscope"]
	cmd = ksdiff --merge --output \"$MERGED\" --base \"$BASE\" -- \"$LOCAL\" --snapshot \"$REMOTE\" --snapshot
	trustexitcode = true
[merge]
	tool = Kaleidoscope
[difftool "Kaleidoscope"]
	cmd = ksdiff --partial-changeset --relative-path \"$MERGED\" -- \"$LOCAL\" \"$REMOTE\"
[difftool]
	prompt = false
[mergetool]
	prompt = false
[diff]
	tool = Kaleidoscope

도움 사이트: https://help.github.com/articles/setting-your-username-in-git/

pod install에러(could not find compatible versions for...)

|

어느날 평소와 다름 없이 pod install을 했는데 갑자기 원치않는 에러를 또 만나게 되었다. 아니 이건 또 뭐람.

git:(release/develop) $ pod install
Analyzing dependencies
[!] CocoaPods could not find compatible versions for pod "XXXCrashAgent":
  In Podfile:
    IMQACrashAgent (~> 1.3.0)

None of your spec sources contain a spec satisfying the dependency: `XXXCrashAgent (~> 1.3.0)`.

You have either:
 * out-of-date source repos which you can update with `pod repo update` or with `pod install --repo-update`.
 * mistyped the name or version.
 * not added the source repo that hosts the Podspec to your Podfile.

Note: as of CocoaPods 1.0, `pod repo update` does not happen on `pod install` by default.

해결: 싱겁게 끝났다.

$ pod repo update

git 실수로 push한 파일을 히스토리 삭제하기

|

git의 remote 주소를 변경하고 싶을 때

git remote set-url origin git://new.url.here

git 실수로 push한 파일을 히스토리 삭제하기

```

문제의 머지가 발생한 곳에서 임시브랜치를 만들면서 체크하웃 함. (create and check out a temporary branch at the location of the bad merge)

git checkout -b tmpfix <sha1-of-merge>

잘못 추가한 파일을 제거

git rm somefile.orig

commit the amended merge

git commit --amend

master branch 로 이동

git checkout master

replant the master branch onto the corrected merge

git rebase tmpfix

임시 branch 삭제

git branch -d tmpfix

원문: https://github.com/honux77/practice/wiki/git-remove-sensitive-file-from-history