[swift] Swift에서 파일을 다운로드하는 방법
파일을 다운로드하는 기능은 많은 앱에서 필요한 기능 중 하나입니다. Swift에서는 URL을 사용하여 파일을 다운로드할 수 있습니다. 이번 기사에서는 Swift에서 파일을 다운로드하는 간단한 방법을 알아보겠습니다.
1. URLSession을 사용하여 파일 다운로드하기
Swift에서는 URLSession을 사용하여 파일을 다운로드할 수 있습니다. 다음은 URLSession을 사용하여 파일을 다운로드하는 간단한 코드입니다.
if let url = URL(string: "https://example.com/file.jpg") {
let task = URLSession.shared.downloadTask(with: url) { (url, response, error) in
if let error = error {
print("Error: \(error)")
} else {
if let downloadedURL = url {
// 다운로드한 파일의 위치
let destinationURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("file.jpg")
do {
try FileManager.default.moveItem(at: downloadedURL, to: destinationURL)
print("다운로드 완료")
} catch {
print("파일 이동 실패: \(error)")
}
}
}
}
task.resume()
} else {
print("유효하지 않은 URL")
}
위의 코드에서는 URL 객체를 생성하고, URLSession.shared.downloadTask 메서드를 사용하여 다운로드를 수행합니다. 파일을 성공적으로 다운로드하면, 다운로드한 파일을 원하는 위치로 이동시킵니다.
2. 다운로드 진행 상황 표시하기
때로는 파일 다운로드의 진행 상황을 사용자에게 표시해야 할 수도 있습니다. URLSessionDownloadDelegate를 사용하여 파일 다운로드의 진행 상황을 모니터링할 수 있습니다. 다음은 다운로드 진행률을 표시하는 간단한 예시입니다.
class DownloadManager: NSObject, URLSessionDownloadDelegate {
var downloadTask: URLSessionDownloadTask?
func downloadFile(fromURL url: URL) {
let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
downloadTask = session.downloadTask(with: url)
downloadTask?.resume()
}
// 다운로드 진행 상태를 업데이트하는 메서드
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let percentage = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite) * 100
print("다운로드 진행률: \(percentage)%")
}
// 파일 다운로드가 완료된 후 호출되는 메서드
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
// 다운로드한 파일을 원하는 위치로 이동시킴
}
}
위의 코드에서는 URLSessionDownloadDelegate를 구현하여 다운로드 진행 상태를 업데이트하고, 파일 다운로드가 완료된 후 작업을 수행할 수 있도록 합니다.
마무리
Swift에서 파일을 다운로드하는 방법을 간단히 살펴보았습니다. URLSession을 사용하여 파일을 다운로드하고, 다운로드 진행 상황도 표시할 수 있습니다. 이러한 기능을 활용하여 앱에 파일 다운로드 기능을 추가할 수 있습니다.
참고: Apple Developer Documentation - URLSession