SwiftでDropbox APIを活用する特殊案件にぶち当たって
Swift特有のバージョン毎に微妙に何かが違う現象でハマったので、メモ。
Pods入れてから認証まで。
Pods部分はもっとわかりやすい人の解説へどうぞ。
バージョン情報
・Swift version 5.0.1
・Xcode version 10.2.1
Xcodeプロジェクトの作成
Single View Applicationのプロジェクトを適当に作成
Cocoapodsの設定
# Uncomment the next line to define a global platform for your project
# platform :ios, '8.0'
target 'dropCheck' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for dropCheck
pod 'SwiftyDropbox'
end
現バージョンは特に何も指定しなくてOK
Info.plistの設定変更
赤色塗りつぶしは自身のAPIキーを記載
Dropboxアプリの自身のAPIキーはApp Consoleで取得
DropboxClientのインスタンス初期化
AppDelegate.swift
import UIKit
import SwiftyDropbox //追加
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
DropboxClientsManager.setupWithAppKey("自分のAPIキー") //追加
return true
}
画面にログインするボタンを作成
ViewController.swift
import UIKit
import SwiftyDropbox
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// ログインボタンを追加
let signInButton = UIButton(type: UIButton.ButtonType.system)
signInButton.frame = CGRect(x: 10, y: 190, width: 100, height: 30)
signInButton.setTitle("Sign In", for: .normal)
signInButton.addTarget(self, action: #selector(self.signInDropbox), for: .touchUpInside)
self.view.addSubview(signInButton)
}
@objc func signInDropbox(){
if let _ = DropboxClientsManager.authorizedClient {
//既にログイン済みだとクラッシュするのでログアウト
DropboxClientsManager.unlinkClients()
}
DropboxClientsManager.authorizeFromController(UIApplication.shared,
controller: self,
openURL: { (url: URL) -> Void in
UIApplication.shared.openURL(url)
})
}
認証処理
AppDelegate.swift
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
if let authResult = DropboxClientsManager.handleRedirectURL(url) {
switch authResult {
case .success:
print("Success! User is logged into Dropbox.")
case .cancel:
print("Authorization flow was manually canceled by user!")
case .error(_, let description):
print("Error: \(description)")
}
}
return true
一応この3点セットがあればDropbox APIの確認という意味では動く。
動作画面
おわりに
他の言語と違って、
Swiftは調べてもしんどいし、色々な方の解説読みに行くより
結局Gitの英語の説明読みに行ったほうが早く解決する事の方が多い。なんでだろね
そしてそのGitの説明もiOSとかSwiftの修正に追いついていないという現象もついてきて
ダブル、トリプルでハマる…Apple様には逆らえない
参考
・公式
http://dropbox.github.io/SwiftyDropbox/api-docs/latest/
https://github.com/dropbox/SwiftyDropbox/issues/94