導入まではこちら
Dropbox APIをSwift5で使用する方法
バージョン情報
・Swift version 5.0.1
・Xcode version 10.2.1
ダウンロードボタンを設置
ViewController.swift
import UIKit
import SwiftyDropbox
class ViewController: UIViewController {
//イメージビューを追加
let myImageView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//省略
//ダウンロードボタンを追加
let downloadButton = UIButton(type: UIButton.ButtonType.system)
downloadButton.frame = CGRect(x: 10, y: 220, width: 100, height: 30)
downloadButton.setTitle("Download", for: .normal)
downloadButton.addTarget(self, action: #selector(self.downloadDropboxFile), for: .touchUpInside)
self.view.addSubview(downloadButton)
//画像表示エリアの記載
myImageView.frame = CGRect(x: 10, y: 500, width: 200, height: 120)
self.view.addSubview(myImageView)
}
ダウンロード 画面表示処理
ViewController.swift
@objc func downloadDropboxFile() {
//ダウンロード処理
if let client = DropboxClientsManager.authorizedClient {
//ダウンロード先URLを設定
let destination : (URL, HTTPURLResponse) -> URL = { temporaryURL, response in
let directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let UUID = Foundation.UUID().uuidString
var fileName = ""
if let suggestedFilename = response.suggestedFilename {
fileName = suggestedFilename
}
let pathComponent = "\(UUID)-\(fileName)"
return directoryURL.appendingPathComponent(pathComponent)
}
//画面描画処理
client.files.download(path: "/logo.png", destination: destination).response { response, error in
if let (metadata, url) = response {
print("Downloaded file name: \(metadata.name)")
do {
//urlをData型に変換
let data = try Data(contentsOf: url)
//Data型に変換したurlをUIImageに変換
let img = UIImage(data: data)
//UIImageをivに変換
let iv:UIImageView = UIImageView(image:img)
//変換したivをviewに追加
self.view.addSubview(iv)
//表示位置決定
iv.layer.position = CGPoint(x: self.view.bounds.width/2, y: 400.0)
} catch let err {
print("Error : \(err.localizedDescription)")
}
} else {
print(error!)
}
}
}
}