Skip to main content

Downloading Files với Alamofire iOS


Giới thiệu

Với lượng dữ liệu ngày càng tăng được sử dụng bởi các ứng dụng di động, việc hầu hết các ứng dụng tải xuống dữ liệu để hỗ trợ các chức năng ngoại tuyến trở nên phổ biến. Dữ liệu được tải xuống có thể là kết cấu bổ sung để hỗ trợ các trò chơi phức tạp, sách điện tử cho người đọc hoặc tệp nhạc / video cho trình phát video / nhạc. Thông thường, các ứng dụng triển khai trình quản lý tải xuống của riêng họ quên một khía cạnh rất quan trọng của quy trình này là cho phép người dùng tạm dừng tải xuống và tiếp tục lại sau khi họ có kết nối internet tốt hơn.

Downloading Files

iOS hỗ trợ để tải xuống tệp bằng NSURLCconnectection Foundation. Một đối tượng NSURLConnection cho phép bạn tải nội dung của URL bằng cách cung cấp một URL request object. NSURLConnection rất ít chỉ cung cấp các điều khiển cơ bản để bắt đầu tải và hủy không đồng bộ .

Alamofire

Có một số công cụ và thư viện đã được xây dựng để giúp bạn dễ dàng sử dụng hơn. Thay vì dùng NSURLC Connectection, chúng ta hãy thử thiết lập các bản tải xuống bằng cách sử dụng Alamofire giúp đơn giản hóa rất nhiều các tác vụ tải xuống.
Ở đây rất đơn giản để bắt đầu tải các tệp xuống bằng cách sử dụng Alamofire.doad. Để nơi lưu file tải xuống, sử dụng DownloadFileDestination . Cuối cùng, để bắt được các bản cập nhật và tiến độ tải xuống, chúng ta dùng downloadProTHER. Nếu bạn muốn thực hiện một số thay đổi đối với giao diện người dùng (ví dụ: cập nhật tải file), hãy sử dụng DispatchQueue.main.async để thực hiện các cập nhật trên Giao diện người dùng.
private func beginDownload() {  
   UIApplication.shared.isIdleTimerDisabled = true

   self.downloadProgressView?.setProgress(value: 0, animationDuration: 0)

   let destination: DownloadRequest.DownloadFileDestination = {temporaryURL, response in
     if let suggestedFileName = response.suggestedFilename {
       do {
         let directory = try Utils.tempDirectory()
         self.downloadedFilePath = (directory + suggestedFileName)
         if let downloadedFilePath = self.downloadedFilePath {
           if downloadedFilePath.exists { try self.downloadedFilePath?.deleteFile() }
           return (URL(fileURLWithPath: downloadedFilePath.rawValue), [.removePreviousFile, .createIntermediateDirectories])
         }
       } catch let e {
         log.warning("Failed to get temporary directory - \(e)")
       }
     }

     let (downloadedFileURL, _) = DownloadRequest.suggestedDownloadDestination()(temporaryURL, response)
     self.downloadedFilePath = Path(downloadedFileURL.absoluteString)
     return (downloadedFileURL, [.removePreviousFile, .createIntermediateDirectories])
   }

   downloadRequest = Alamofire.download(url, to:destination).downloadProgress {progress in
     DispatchQueue.main.async {
         self.downloadProgressView?.setProgress(value: CGFloat(progress.fractionCompleted * 100), animationDuration: 0.1)
     }
   }.response { defaultDownloadResponse in
     // TODO: Handle cancelled error
     if let error = defaultDownloadResponse.error {
         log.warning("Download Failed with error - \(error)")
         self.onError(.Download)
         return
     }
     guard let downloadedFilePath = self.downloadedFilePath else { return }
     log.debug("Downloaded file successfully to \(downloadedFilePath)")
     // TODO: Handle downloaded file
   }
 }

Common File Utilities

Tôi thường sử dụng các chức năng tiện ích phổ biến để truy cập các vị trí thư mục trong toàn bộ ứng dụng (Đây là sử dụng Đường dẫn từ FileKit, vì vậy hãy đảm bảo bạn thêm nó vào Podfile hoặc Cartfile nếu bạn cũng dự định sử dụng các tiện ích này).
class Utils {  
  internal static func tempDirectory() throws -> Path {
    return try self.directoryInsideDocumentsWithName(name: "temp")
  }

  internal static func directoryInsideDocumentsWithName(name: String, create: Bool = true) throws -> Path {
   let directory = Path(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]) + name
   if create && !directory.exists {
     try directory.createDirectory()
   }
   return directory
  }
}
Tất cả những gì bạn cần để tích hợp một thành phần tải xuống đơn giản trong ứng dụng của bạn sử dụng Alamofire đơn giản hơn rất nhiều. Bài sau sẽ nói về cách Resuming downloads bằng Alamofire .

Comments

Popular posts from this blog

Swift GCD part 1: Thread safe singletons

Preview Singletons are entities, referenced to the same instance of a class from everywhere in your code. It doesn't matter if you like them or not, you will definitely meet them, so it's better to understand how they work. Constructing and handling a set of data doesn't seem to be a big challenge at first glance. The problems appear when you try to optimise the user experience with background work and your app starts acting weird. ??‍♂️ After decades of watching your display mostly with a blank face, you finally realize that your data isn't handled consistently by the manager because you're accessing it (running tasks on it) from multiple threads at the same time. So you really do have to deal with making your singletons thread safe. This article series is dedicated to thread handling using Swift. In the first part below you will get a comprehensive insight into som...

Kiến thức cơ bản về RxSwift

Bài viết với mong muốn cung cấp thông tin cơ bản về kiến trúc, các thuật ngữ được sử dụng phổ biến về RxSwift, giúp những lập trình viên lần đầu làm quen RxSwift sẽ trở nên dễ dàng hơn. Trong bài viết có sử dụng một số từ khóa tiếng Anh, mình xin phép sẽ giữ nguyên bản không sử dụng tiếng Việt vì có lẽ sẽ dễ hiểu hơn cho người đọc. Observable Sequences Mọi hoạt động trong RxSwift từ việc đăng ký và xử lý sự kiện đều thông qua một Observable Sequences Trong RxSwift , các kiểu dữ liệu như Arrays , Strings hoặc Dictionary sẽ được convert sang Observable Sequences . Ta có thể tạo ra "Observable Sequences" của bất kỳ kiểu đối tượng nào tuân theo Sequence Protocol của Swift Standard Library . let helloSequence = Observable.just( "Hello Rx" ) let fibonacciSequence = Observable. from ([ 0 , 1 , 1 , 2 , 3 , 5 , 8 ]) let dictSequence = Observable. from ([ 1 : "Hello" , 2 : "World" ]) Đăng ký nhận event từ ""Observable Se...

Thread safe singleton’s in Swift

What are singletons? — Singleton is design patterns which says that there should be only one instance of the class for the lifetime of the application. One the best example of Singleton is AppDelegate . How to write a singleton class ? class DefaultDict{ private var dict:[String:Any] = [:] public static let sharedManager = DefaultDict() private init(){ } public func set(value:Any,key:String){ dict[key] = value } public func object(key:String) -> Any?{ dict[key] } public func reset(){ dict.removeAll() } }   Testing singleton class under concurrent circumstances. We are going to write an example where we will set values in dict from various threads and even try to access some with different threads. When we do this we will encounter a crash. If you look closely it will be because of race condition and the crash will be on line set(value:Any,key:String) . class ViewController: UIViewController { ...