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

Alamofire vs URLSession

Alamofire vs URLSession: a comparison for networking in Swift Alamofire and URLSession both help you to make network requests in Swift. The URLSession API is part of the foundation framework, whereas Alamofire needs to be added as an external dependency. Many  developers  doubt  whether it’s needed to include an extra dependency on something basic like networking in Swift. In the end, it’s perfectly doable to implement a networking layer with the great URLSession API’s which are available nowadays. This blog post is here to compare both frameworks and to find out when to add Alamofire as an external dependency. Build better iOS apps faster Looking for a great mobile CI/CD solution that has tons of iOS-specific tools, smooth code signing, and even real device testing? Learn more about Bitrise’s iOS specific solutions! This shows the real power of Alamofire as the framework makes a lot of things easier. What is Alamofire? Where URLSession...

Swift Tool Belt, Part 1: Adding a Border, Corner Radius, and Shadow to a UIView with Interface Builder

During my iOS work, I’ve assembled a set of code that I bring with me on every iOS project. I’m not talking about large frameworks or CocoaPods here. These are smaller Swift extensions or control overrides that are applicable to many projects. I think of them as my tool belt. In this post, I’ll show you an extension that will add a border, a corner radius, and a shadow to any UIView, UIButton, or UILabel and allow you to preview what it will look like in Interface Builder. Back in 2014, I wrote a blog post on Expanding User-Defined Runtime Attributes in Xcode where I added a border, corner radius, and shadow to a UIView using Interface Builder’s user-defined runtime attributes. This solution had no type checking—you had to type the property you wanted to modify by hand and often had to look up what it was called. You also had to run your project in order to see the effect of the runtime attribute. Starting with Xcode 6 , there is a new mech...

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