Project 17 - NSURLConnection

DaY·2021년 5월 7일
1

iOS

목록 보기
39/52
post-thumbnail

iOS에서 json 형태를 이용해 http 통신을 하는 방법 중 NSURLConnection을 사용하여 동기적 통신을 수행할 수 있다.
NSURLConnection Delegate를 이용하면 다양한 방법으로 통신을 컨트롤 가능하다.

NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) { response, data, error in
    if let data = data {
        do {
            if let datasourceDictionary = try PropertyListSerialization.propertyList(from: data, options: PropertyListSerialization.ReadOptions(rawValue: 0), format: nil) as? [String: AnyObject] {

                for (name, url) in datasourceDictionary {
                    if let url = URL(string: url as! String) {
                        let photoRecord = PhotoRecord(name: name, url: url)

                        self.photos.append(photoRecord)
                    }
                }
                self.tableView.reloadData()
            }
        } catch let error as NSError {
                print(error.domain)
        }
    }
    UIApplication.shared.isNetworkActivityIndicatorVisible = false
}

NSURLConnection 수행 시 오류 해결

다음과 같은 코드로 오류 발생 시 알람이 뜨도록 하였다.

if let error = error {
    let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
    let cancel = UIAlertAction(title: "OK", style: .cancel, handler: nil)

    alert.addAction(cancel)
    self.present(alert, animated: true, completion: nil)

    return
}

인증되지 않은 HTTP 또는 HTTPS로 이동하거나 webView를 띄우면 위와 같은 에러가 발생한다.

App Transport Security

  • 응용 프로그램과 웹 서비스 간의 안전한 연결을 위함.
  • ATS가 활성화되면 HTTP를 통해 통신을 할 수 없다.
  • 권장되는 요구사항을 충족하지 않는 연결은 강제로 연결 실패 처리된다.

Info.plist에서
App Transport Security Settings를 입력하고 하위에 Allow Arbitary Loads를 허용해줌으로써 해결 가능하다.

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoadsInWebContent</key>
    <true/>
    <key>NSAllowsArbitraryLoadsForMedia</key>
    <true/>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

0개의 댓글