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

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

Frame vs Bounds in iOS

This article is a repost of an answer I wrote on Stack Overflow . Short description frame = a view’s location and size using the parent view’s coordinate system ( important for placing the view in the parent) bounds = a view’s location and size using its own coordinate system (important for placing the view’s content or subviews within itself) Details To help me remember frame , I think of a picture frame on a wall . The picture frame is like the border of a view. I can hang the picture anywhere I want on the wall. In the same way, I can put a view anywhere I want inside a parent view (also called a superview). The parent view is like the wall. The origin of the coordinate system in iOS is the top left. We can put our view at the origin of the superview by setting the view frame’s x-y coordinates to (0, 0), which is like hanging our picture in the very top left corner of the wall. To move it right, increase x, to move it down increase y. To help me remember bound...