[swift] 파일을 인터넷을 통해 다운로드하는 방법
파일을 인터넷을 통해 다운로드하는 방법은 Swift 언어로 쉽게 구현할 수 있습니다. URLSession을 사용하여 파일을 다운로드할 수 있으며, 다운로드가 완료될 때마다 알림을 받을 수 있습니다.
1. URLSession을 사용하여 파일 다운로드
import Foundation
// 다운로드할 파일의 URL
let fileURL = URL(string: "https://www.example.com/file.zip")!
let downloadTask = URLSession.shared.downloadTask(with: fileURL) { (location, response, error) in
guard let location = location, error == nil else {
// 다운로드 중 에러 발생
print("다운로드 중 에러 발생: \(error)")
return
}
// 다운로드가 완료된 파일이 위치한 임시 디렉토리 경로
let destinationURL = URL(fileURLWithPath: "/path/to/destination/file.zip")
do {
// 다운로드 완료된 파일을 목적지 디렉토리로 이동
try FileManager.default.moveItem(at: location, to: destinationURL)
print("파일 다운로드 완료: \(destinationURL)")
} catch {
print("파일을 이동하는 동안 에러 발생: \(error)")
}
}
downloadTask.resume() // 다운로드 시작
위의 코드에서는 URLSession을 사용하여 파일을 다운로드합니다. 다운로드가 완료되면 임시 디렉토리에 있는 파일을 목적지 디렉토리로 이동시킵니다.
2. 다운로드 진행 상황 감지
다운로드의 진행 상황을 감지하고 싶다면, URLSessionDownloadDelegate 프로토콜을 채택한 후 다음 메서드를 구현할 수 있습니다.
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
// 진행 상황 처리 로직
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
// 다운로드 완료 처리 로직
}
이렇게 하면 파일을 다운로드하는 동안의 상태를 실시간으로 감시할 수 있습니다.
위와 같은 방법으로 Swift를 사용하여 인터넷을 통해 파일을 다운로드할 수 있습니다.
참고 자료
- Apple Developer Documentation. “URLSession.” 링크
- Swift.org. “The Swift Programming Language.” 링크
- Hacking with Swift. “How to download a file with URLSession.” 링크