iOSkingkr / Giftatte22

선물 어플을 개발할꺼에요
3 stars 0 forks source link

Parsing 한 문자열 주소를 지정된 URL에서 리소스를 비동기식으로 열기 #20

Open DevKDuck opened 2 years ago

DevKDuck commented 2 years ago
스크린샷 2022-05-25 오후 4 35 20

컬렉션 뷰에서 셀을 선택하였을 경우 URL에서 리소스를 비동기식으로 여는 방식을 구현하고 싶었다.

셀 선택을 하였을때 실행이 되어야 하기 때문에 didSelectItemAt함수에서 구현을 하였다.

스크린샷 2022-05-25 오후 4 36 57
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
    if let url = URL(string: onboardingDataArray[indexPath.row].webUrl){
    UIApplication.shared.open(url, options[:])
    }
}

위와 같이 코드를 작성했지만 URL창이 열리지 않았다. else문을 추가해서 함수가 잘실행되는지 확인해 보았다.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
    if let url = URL(string: onboardingDataArray[indexPath.row].webUrl){
    UIApplication.shared.open(url, options: [:])
    }else{
         print("else문일 떄 나타나는 문장\(onboardingDataArray[indexPath.row].webUrl)")
       }
}
스크린샷 2022-05-25 오후 4 50 15

else 문으로 빠지는것을 확인했다.

if 문이 작동이 안되는 이유를 확인해 보았다 . 먼저 string 뒤에 값을 네이버 주소로 바꾸어보았다 .

if let url = URL(string: "https://www.naver.com")
실행이 잘되었다 . 
<img width="282" alt="스크린샷 2022-05-25 오후 4 52 59" src="https://user-images.githubusercontent.com/96559947/170210502-23d9d47f-938c-4468-93e6-21d855245512.png">

문자열로 받는 부분이 잘못된 것 같다고 생각했다

DevKDuck commented 2 years ago

문제 원인 : string 문자열을 URL로 바꾸는 과정에서 스페이스 공백이나 한글이 들어갔을때 url이 nil이 될 수 있다

해결 방법 : 인코딩을 하면 된다. addingPercentEncoding이 하는일은 지정된 Set에 없는 모든 문자를 백분율로 인코딩된 문자로 바꾸어 새로운 문자열을 반환해주는 함수이다 위에서 encoded는 String타입이 되는것이고 그걸 URL타입으로 바꾼것이 myURL이다 .


    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        if let encoded = onboardingDataArray[indexPath.row].webUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let myURL = URL(string: encoded){
            UIApplication.shared.open(myURL, options: [:])
        }
    }
}