[TIL] 2024. 07. 11

2024. 7. 12. 04:16·TIL (Today I Learned)

URLSession Error Handling

Swift에서 URLSession을 사용할 때 발생할 수 있는 다양한 오류를 처리하는 방법은 중요합니다. 오류 처리 방법을 제대로 이해하고 구현하면, 네트워크 요청이 실패했을 때 적절한 대응을 할 수 있습니다.

URLSession의 기본 오류 처리

URLSession의 콜백 함수에는 error 매개변수가 포함되어 있으며, 이 매개변수를 사용하여 오류를 확인할 수 있습니다. 또한, HTTP 응답 상태 코드를 확인하여 서버에서 발생한 오류도 처리할 수 있습니다.

오류 처리 예제

기본 데이터 작업 오류 처리

let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
    // 네트워크 오류 처리
    if let error = error {
        print("Network error: \(error.localizedDescription)")
        return
    }
    
    // HTTP 응답 상태 코드 처리
    if let httpResponse = response as? HTTPURLResponse {
        if httpResponse.statusCode != 200 {
            print("HTTP error: Status code \(httpResponse.statusCode)")
            return
        }
    }
    
    // 데이터 처리
    guard let data = data else {
        print("No data received")
        return
    }
    
    do {
        let json = try JSONSerialization.jsonObject(with: data, options: [])
        print("JSON response: \(json)")
    } catch {
        print("JSON parsing error: \(error.localizedDescription)")
    }
}
task.resume()​

다운로드 작업 오류 처리

let url = URL(string: "https://example.com/file.zip")!
let task = URLSession.shared.downloadTask(with: url) { location, response, error in
    // 네트워크 오류 처리
    if let error = error {
        print("Network error: \(error.localizedDescription)")
        return
    }
    
    // HTTP 응답 상태 코드 처리
    if let httpResponse = response as? HTTPURLResponse {
        if httpResponse.statusCode != 200 {
            print("HTTP error: Status code \(httpResponse.statusCode)")
            return
        }
    }
    
    // 파일 위치 확인 및 저장
    guard let location = location else {
        print("No file location")
        return
    }
    
    do {
        let documentsURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        let savedURL = documentsURL.appendingPathComponent(response?.suggestedFilename ?? "file.zip")
        try FileManager.default.moveItem(at: location, to: savedURL)
        print("File saved to: \(savedURL)")
    } catch {
        print("File saving error: \(error.localizedDescription)")
    }
}
task.resume()

업로드 작업 오류 처리

let url = URL(string: "https://api.example.com/upload")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let fileURL = Bundle.main.url(forResource: "file", withExtension: "txt")!

let task = URLSession.shared.uploadTask(with: request, fromFile: fileURL) { data, response, error in
    // 네트워크 오류 처리
    if let error = error {
        print("Network error: \(error.localizedDescription)")
        return
    }
    
    // HTTP 응답 상태 코드 처리
    if let httpResponse = response as? HTTPURLResponse {
        if httpResponse.statusCode != 200 {
            print("HTTP error: Status code \(httpResponse.statusCode)")
            return
        }
    }
    
    // 데이터 처리
    guard let data = data else {
        print("No data received")
        return
    }
    
    if let responseString = String(data: data, encoding: .utf8) {
        print("Response: \(responseString)")
    }
}
task.resume()

일반적인 오류 유형

  1. 네트워크 연결 오류: 네트워크 연결이 끊기거나 서버에 도달할 수 없는 경우 발생합니다. error 매개변수에 오류가 전달됩니다.
  2. HTTP 상태 코드 오류: 서버에서 응답을 받았으나, 상태 코드가 2xx 범위가 아닌 경우 발생합니다. HTTPURLResponse의 statusCode를 확인하여 처리합니다.
  3. 데이터 없음: 서버에서 응답을 받았으나 데이터가 없는 경우 발생합니다. data 매개변수가 nil인 경우 처리합니다.
  4. JSON 파싱 오류: 데이터를 JSON으로 변환하는 과정에서 발생하는 오류입니다. JSONSerialization의 try 블록에서 발생한 오류를 처리합니다.
  5. 파일 저장 오류: 다운로드한 파일을 저장하는 과정에서 발생하는 오류입니다. FileManager 작업에서 발생한 오류를 처리합니다.

네트워크 재시도 로직

네트워크 요청이 실패할 때 재시도하는 로직을 추가할 수 있습니다. 이는 일시적인 네트워크 문제를 극복하는 데 유용합니다.

func fetchData(with url: URL, retryCount: Int = 3) {
    let task = URLSession.shared.dataTask(with: url) { data, response, error in
        if let error = error {
            print("Network error: \(error.localizedDescription)")
            if retryCount > 0 {
                print("Retrying... (\(retryCount) attempts left)")
                fetchData(with: url, retryCount: retryCount - 1)
            }
            return
        }
        
        if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
            print("HTTP error: Status code \(httpResponse.statusCode)")
            return
        }
        
        guard let data = data else {
            print("No data received")
            return
        }
        
        // 데이터 처리
    }
    task.resume()
}

let url = URL(string: "https://api.example.com/data")!
fetchData(with: url)

 

이와 같이 Swift의 URLSession을 사용하여 다양한 네트워크 오류를 처리하고, 요청을 재시도하는 로직을 추가하여 네트워크 통신의 신뢰성을 높일 수 있습니다.

반응형

'TIL (Today I Learned)' 카테고리의 다른 글

[TIL] 2024. 07. 15  (0) 2024.07.15
[TIL] 2024. 07. 12  (0) 2024.07.12
[TIL] 2024. 07. 10  (0) 2024.07.10
[TIL] 2024. 07. 09  (0) 2024.07.09
[TIL] 2024. 07. 08  (0) 2024.07.08
'TIL (Today I Learned)' 카테고리의 다른 글
  • [TIL] 2024. 07. 15
  • [TIL] 2024. 07. 12
  • [TIL] 2024. 07. 10
  • [TIL] 2024. 07. 09
DongDong_
DongDong_
  • DongDong_
    how-dev
    DongDong_
  • 전체
    오늘
    어제
    • 분류 전체보기 (102)
      • TIL (Today I Learned) (96)
      • DEV (0)
        • 알고리즘 (0)
        • SWIFT (0)
      • 사전캠프 데일리 미션 (5)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 글작성
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
DongDong_
[TIL] 2024. 07. 11
상단으로

티스토리툴바