Swift Photo App

minio_SWIFT1

本示例将会指导你使用Swift构建一个简单的Photo app。在这个app中,你将会学习一个Swift client是如何访问Photo API Service并随机加载一张图片。你可以通过这里获取完整的代码,代码是以Apache 2.0 License发布的。

1. 依赖

我们将使用Xcode7.0和Swift2.0来构建这个app。这个app也会访问我们发布的Photo API Service来随机获获取一张图片的presigned url。

  • Xcode 8.3 Beta
  • Swift 3.1

    2. 设置

启动Xcode并完成下列步骤。

  • 步骤1 - 创建一个新的工程,选择Single View Application,点击Next。
    minio_SWIFT2

  • 步骤2 - 输入Project Name,Organization Name和Identifiers。我们在本示例中用的是下图所示的值,你想改的话请便。点击Next。
    minio_SWIFT3

  • 步骤3 - 现在一个空的MainStoryBoard已经准备就绪。
    minio_SWIFT4

3. MainStoryBoard

  • 拖拽一个UIButton到这个StoryBoard。
  • 拖拽一个imageView到这个StoryBoard。
  • 如果你不太喜欢它们的背景色的话,你可以改成你喜欢的颜色。
    minio_SWIFT5

4. ViewController.swift

我们将会用到之前构建的Phtoto API Service来给我们的SwiftPhotoApp提供服务。为了简单起见,我们没有用到TableView或者是CollectionView来显示图片列表,我们只是从PhotoAPI Service返回的多个presigned URL中随机选一个进行加载。

  1. import UIKit
  2. class ViewController: UIViewController {
  3. @IBAction func refButton(sender: UIButton) {
  4. // Set up the URL Object.
  5. let url = URL(string: "http://play.minio.io:8080/PhotoAPIService-0.0.1-SNAPSHOT/minio/photoservice/list")
  6. // Task fetches the url contents asynchronously.
  7. let task = URLSession.shared.dataTask(with: url! as URL) {(data, response, error) in
  8. let httpResponse = response as! HTTPURLResponse
  9. let statusCode = httpResponse.statusCode
  10. // Process the response.
  11. if (statusCode == 200) {
  12. do{
  13. // Get the json response.
  14. let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:AnyObject]
  15. // Extract the Album json into the albums array.
  16. if let albums = json["Album"] as? [[String: AnyObject]]{
  17. // Pick a random index from the albums array.
  18. let randomIndex = Int(arc4random_uniform(UInt32(albums.count)))
  19. // Extract the url from the albums array using this random index we generated.
  20. let loadImageUrl:String = albums[randomIndex]["url"] as! String
  21. // Prepare the imageView.
  22. self.imageView.contentMode = .scaleAspectFit
  23. // Download and place the image in the image view with a helper function.
  24. if let checkedUrl = URL(string: loadImageUrl) {
  25. self.imageView.contentMode = .scaleAspectFit
  26. self.downloadImage(url: checkedUrl)
  27. }
  28. }
  29. }
  30. catch {
  31. print("Error with Json: \(error)")
  32. }
  33. }
  34. }
  35. task.resume()
  36. }
  37. @IBOutlet weak var imageView: UIImageView!
  38. override func viewDidLoad() {
  39. super.viewDidLoad()
  40. // Do any additional setup after loading the view, typically from a nib.
  41. }
  42. override func didReceiveMemoryWarning() {
  43. super.didReceiveMemoryWarning()
  44. // Dispose of any resources that can be recreated.
  45. }
  46. // Asynchronous helper function that fetches data from the PhotoAPIService.
  47. func getDataFromUrl(url:URL, completion: @escaping ((_ data: Data?, _ response: URLResponse?, _ error: Error? ) -> Void)) {
  48. URLSession.shared.dataTask(with: url as URL) { (data, response, error) in
  49. completion(data, response, error)
  50. }.resume()
  51. }
  52. // Helper function that download asynchronously an image from a given url.
  53. func downloadImage(url: URL){
  54. getDataFromUrl(url: url) { (data, response, error) in
  55. DispatchQueue.main.async() { () -> Void in
  56. guard let data = data, error == nil else { return }
  57. self.imageView.image = UIImage(data: data as Data)
  58. }
  59. }
  60. }
  61. }

5. Info.plist

我们需要在info.plist文件中添加权限,这样的话app才能从play服务上获取URL和图片。

minio_SWIFT6

以下是完整的info.plist文件。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  3. <plist version="1.0">
  4. <dict>
  5. <key>CFBundleDevelopmentRegion</key>
  6. <string>en</string>
  7. <key>CFBundleExecutable</key>
  8. <string>$(EXECUTABLE_NAME)</string>
  9. <key>CFBundleIdentifier</key>
  10. <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
  11. <key>CFBundleInfoDictionaryVersion</key>
  12. <string>6.0</string>
  13. <key>CFBundleName</key>
  14. <string>$(PRODUCT_NAME)</string>
  15. <key>CFBundlePackageType</key>
  16. <string>APPL</string>
  17. <key>CFBundleShortVersionString</key>
  18. <string>1.0</string>
  19. <key>CFBundleSignature</key>
  20. <string>????</string>
  21. <key>CFBundleVersion</key>
  22. <string>1</string>
  23. <key>LSRequiresIPhoneOS</key>
  24. <true/>
  25. <key>UILaunchStoryboardName</key>
  26. <string>LaunchScreen</string>
  27. <key>UIMainStoryboardFile</key>
  28. <string>Main</string>
  29. <key>UIRequiredDeviceCapabilities</key>
  30. <array>
  31. <string>armv7</string>
  32. </array>
  33. <key>UISupportedInterfaceOrientations</key>
  34. <array>
  35. <string>UIInterfaceOrientationPortrait</string>
  36. <string>UIInterfaceOrientationLandscapeLeft</string>
  37. <string>UIInterfaceOrientationLandscapeRight</string>
  38. </array>
  39. <key>NSAppTransportSecurity</key>
  40. <dict>
  41. <key>NSExceptionDomains</key>
  42. <dict>
  43. <key>play.minio.io</key>
  44. <dict>
  45. <key>NSIncludesSubdomains</key>
  46. <true/>
  47. <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
  48. <true/>
  49. <key>NSTemporaryExceptionMinimumTLSVersion</key>
  50. <string>1.0</string>
  51. <key>NSTemporaryExceptionRequiresForwardSecrecy</key>
  52. <false/>
  53. </dict>
  54. </dict>
  55. </dict>
  56. </dict>
  57. </plist>

7. 运行App

原文: https://docs.minio.io/cn/swift-photo-app.html