Created
November 3, 2019 00:20
-
-
Save gauravparvadiya/113f810da0c7a99b1f2992370c231137 to your computer and use it in GitHub Desktop.
File downloading in Swift 5 using URLSession
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
class StorageManager { | |
static let shared = StorageManager() | |
private init() {} | |
} | |
// MARK: - Remote Config storage methods | |
extension StorageManager { | |
func getFileLastDownloadedDate() -> Date { | |
return UserDefaults.standard.object(forKey: "fileLastDownloadedDate") as? Date ?? Date(timeIntervalSince1970: 0) | |
} | |
func setFileLastDownloadedDate(_ date: Date) { | |
UserDefaults.standard.set(date, forKey: "fileLastDownloadedDate") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class URLTask { | |
static let shared = URLTask() | |
private init() {} | |
// Checks if file at given URL is modified. | |
// Using "Last-Modified" header value to compare it with given date. | |
func checkFileModifiedAt(_ url: URL, completion: @escaping (Bool, Date?) -> Void) { | |
var request = URLRequest(url: url) | |
request.httpMethod = "HEAD" | |
URLSession.shared.dataTask(with: request, completionHandler: { (_, response, error) in | |
guard let httpURLResponse = response as? HTTPURLResponse, | |
httpURLResponse.statusCode == 200, | |
let modifiedDateString = httpURLResponse.allHeaderFields["Last-Modified"] as? String, | |
let modifiedDate = modifiedDateString.toDate(), | |
error == nil | |
else { | |
completion(false, nil) | |
return | |
} | |
if modifiedDate > StorageManager.shared.getFileLastDownloadedDate() { | |
completion(true, modifiedDate) | |
return | |
} | |
completion(false, nil) | |
}).resume() | |
} | |
// Downloads file from given URL and store it at temporary location. | |
// It is possible that iOS will remove temp files very often so highly | |
// recommended to move file to any permanent location. | |
func downloadFile(from url: URL, onSuccess: @escaping (URL) -> Void, onError: @escaping (Error?) -> Void) { | |
URLSession.shared.downloadTask(with: url, completionHandler: { (downloadLocation, response, error) in | |
guard let httpURLResponse = response as? HTTPURLResponse, | |
httpURLResponse.statusCode == 200, | |
let downloadLocation = downloadLocation, | |
error == nil | |
else { | |
onError(error) | |
return | |
} | |
onSuccess(downloadLocation) | |
}).resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment