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

RxSwift - Giới thiệu

Bạn có nghe qua về Reactive Programming chưa, đây là một khái niệm lập trình hoàn toàn mới. “Reactive Programming là lập trình theo hướng bất đồng bộ các dòng chảy dữ liệu(data streams)” Sau khi đọc khái niệm các bạn có lẽ rất mơ hồ, vậy các data streams là gì. Vậy để mình ví dụ cho các bạn: - Trong lập trình bình thường ( imperative programming ) a = b + c , tức a được gắn với kết quả cộng của b và c .Khi b với c thay đổi thì tất nhiên sẽ không ảnh hưởng tới a, nhưng trong Reactive Programming này a sẽ tự động thay đổi khi b hoặc c thay đổi, kết quả của a sẽ lập tức thay đổi theo. Vậy tại sao nên dùng RXSwift: + Giúp ứng dụng của bạn hoạt động 1 cách như là real time update ui khi có thay đổi data flow, mang đến trải nghiệm tuyệt vời cho User. + Dễ dàng lập trình bất đồng bộ (Async) thay vì phải dùng : callbacks, delegates, notifications, kvo… Bạn phải dùng nhiều thứ gây ra ứng dụng của bạn phức tạp, khó kiểm soát. + Chuyển đổi các thread khi thực hiện 1 cách...

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...

Enum Initializers

In Swift Talk 45 , we wrote a small library for parsing routes. We represented routes as enums, and added a custom initializer to parse routes: enum Route { case home case users(id: Int ) } extension Route { init ?(path: String ) { if path == "/" { self = .home } else if path.hasPrefix( "/users" ) { self = .users(id: 1 ) } else { return nil } } } Of course, this code isn’t complete (see the full public episode for that). Today, we want to focus on assigning to self inside the initializer. In the initializer of any struct or enum we can treat self as a mutable variable (as if it were declared using inout ). This is why we can do the following: enum Result < A > { case success( A ) case error( Error ) } extension Result { init ( _ value: A ) { self = .success(value) } } We can even do this in a struct, although it’s easie...