투케이2K

520. (ios/swift5) URLSession downloadTask 사용해 실시간 파일 다운로드 진행 상태 확인 - URLSessionDownloadDelegate 본문

IOS

520. (ios/swift5) URLSession downloadTask 사용해 실시간 파일 다운로드 진행 상태 확인 - URLSessionDownloadDelegate

투케이2K 2024. 4. 26. 09:49
반응형

[개발 환경 설정]

개발 툴 : XCODE

개발 언어 : SWIFT5

 

[소스 코드]

    // -----------------------------------------------------------------------------------------
    // MARK: - [테스트 메인 함수 정의 실시]
    // -----------------------------------------------------------------------------------------
    func testMain() {
        S_Log._D_(description: "테스트 함수 시작 실시", data: nil)
        
        
        /*
        // -------------------------------------------------------
        [요약 설명]
        // -------------------------------------------------------
        1. 필요 info plist 설정
         
         http 허용 : App Transport Security Settings >> Allow Arbitrary Loads >> YES
        // -------------------------------------------------------
        2. 필요 딜리게이트 : URLSessionDownloadDelegate
         
         ex : ViewController: UIViewController, URLSessionDownloadDelegate
        // -------------------------------------------------------
        */
        
        
        // [로직 처리 실시]
        DispatchQueue.main.async {
            
            
            // -----------------------------------------
            // [HTTP 요청 주소 정의]
            // -----------------------------------------
            let urlData = "http://dev.twok.co.kr:5800/FileTest/test.png"
            
            
            // -----------------------------------------
            // [URLRequest 생성 실시]
            // -----------------------------------------
            let urlComponents = URLComponents(string: urlData)
            var requestURL = URLRequest(url: (urlComponents?.url)!)
            
            requestURL.httpMethod = "GET"
            
            requestURL.addValue("application/x-www-form-urlencoded; charset=utf-8;", forHTTPHeaderField: "Content-Type") // header settings
            requestURL.addValue("no-cache", forHTTPHeaderField: "Cache-Control") // header settings
            
            
            S_Log._D_(description: "파일 다운로드 GET 방식 HTTP [요청] 수행", data: [
                "TYPE :: GET >> REQUEST",
                "URL :: " + String(describing: urlData)
            ])
            
            
            // -----------------------------------------
            // [http 요쳥을 위한 URLSessionDataTask 생성]
            // -----------------------------------------
            let sessionConfig = URLSessionConfiguration.default
            sessionConfig.timeoutIntervalForRequest = 30 // [커넥션 타임 아웃 설정]
            //sessionConfig.timeoutIntervalForResource = 30 // [리소스 읽기 , 쓰기]
            
            let session = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
            
            
            // -----------------------------------------
            // [파일 다운 로드 요청 수행]
            // -----------------------------------------
            let downloadTask = session.downloadTask(with: requestURL)
            
            downloadTask.resume() // [network 통신 실행]
            
        }

    }
    
    
    
    
    
    // -----------------------------------------------------------------------------------------
    // MARK: - [URLSessionDownloadDelegate] : [파일 다운로드 완료 상태 체크]
    // -----------------------------------------------------------------------------------------
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        //S_Log._D_(description: "URLSessionDownloadDelegate >> didFinishDownloadingTo :: 파일 다운로드 완료 상태", data: nil)
        
        do {
        
            // [Data 읽기 수행]
            let data = try Data(contentsOf: location, options: [.mappedIfSafe])
            
            // [Data 이미지 변환]
            let image : UIImage = UIImage(data: data)!
            
            // [이미지 표시]
            self.observableImage(title: "파일 다운로드 확인", image: image, okBtn:"확인", noBtn: "취소"){(result) in
                
                S_Log._D_(description: "이미지 팝업창 버튼 클릭 콜백 결과 확인", data: ["\(result)"])
                
            }
            
        } catch {
            S_Log._D_(description: "URLSessionDownloadDelegate >> didFinishDownloadingTo :: 파일 저장 에러 발생", data: [
                "catch :: \(error.localizedDescription)"
            ])
        }
    }
    
    
    
    
    
    // -----------------------------------------------------------------------------------------
    // MARK: - [URLSessionDownloadDelegate] : [파일 다운로드 완료 및 에러 상태 체크]
    // -----------------------------------------------------------------------------------------
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        
        guard error == nil else {
            S_Log._D_(description: "URLSessionDownloadDelegate >> didCompleteWithError :: 파일 다운로드 에러 발생", data: [
                "ERROR :: \(error?.localizedDescription ?? "")"
            ])
            
            // [리턴 반환]
            return
        }
        
        
        // [status 코드 체크 실시]

        let successsRange = 200..<300
        guard let statusCode = (task.response as? HTTPURLResponse)?.statusCode, successsRange.contains(statusCode)
        else {
            S_Log._D_(description: "URLSessionDownloadDelegate >> didCompleteWithError :: 파일 다운로드 에러 발생", data: [
                "STATUS CODE :: " + String(describing: (task.response as? HTTPURLResponse)?.statusCode ?? 0),
                "RESPONSE DATA :: \((task.response as? HTTPURLResponse)?.description ?? "")"
            ])
            
            // [리턴 반환]
            return
        }

        
        // [response 데이터 획득]
        let resultCode = (task.response as? HTTPURLResponse)?.statusCode ?? 0
        let resultMime = task.response?.mimeType ?? ""
        
        S_Log._D_(description: "URLSessionDownloadDelegate >> didCompleteWithError :: 파일 다운로드 상태 확인", data: [
            "STATUS_CODE :: \(resultCode)",
            "RESPONSE_MIME :: \(resultMime)"
        ])
    }
    
    
    
    
    
    // -----------------------------------------------------------------------------------------
    // MARK: - [URLSessionDownloadDelegate] : [파일 다운로드 진행 상태 체크]
    // -----------------------------------------------------------------------------------------
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        
        let currentProgress = ( Float(totalBytesWritten) / Float(totalBytesExpectedToWrite) ) * 100
        let totalSize = ByteCountFormatter.string(fromByteCount: totalBytesExpectedToWrite, countStyle: .file)

        S_Log._D_(description: "URLSessionDownloadDelegate >> totalBytesExpectedToWrite :: 파일 다운로드 진행 상태 확인", data: [
            "Progress :: \(currentProgress)",
            "TotalSize :: \(totalSize)"
        ])
        
    }
 

[결과 출력]


반응형
Comments