今回の記事はGoogleDriveAPIを使ってファイルをアップロードする方法に関する記事です。初心者にもわかりやすいように記載していくので是非参考にしてみて下さい。
GoogleDriveAPIを使用できるように設定
まずはGoogleDriveAPIにて設定を行い、アプリからGoogleDriveにログインするところまで完了させましょう。
下記記事を参考にしてみて下さい。
「【Swift】GoogleDriveAPIを使ってDrive内のファイル一覧を取得する方法ご紹介。」
上記工程でログインを行い、ログインユーザに自身のログイン情報を設定しましょう。
GoogleDriveAPIを使ってファイルをアップロード
編集するファイルは「Appdelegate.swift」「ViewController.Swift」の2点です。順番に説明していきます。
「Appdelegate.swift」を編集
- ローカルに保存したplistの中の「CLIENT_ID」の値を下記に追加
- 関数の追加
import UIKit
import GoogleSignIn
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
// 元々ある関数
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// 追加(クライアントID)
GIDSignIn.sharedInstance().clientID = "〇〇.apps.googleusercontent.com"
return true
}
// 追加関数
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
// GIDSignInのhandle()を呼び、返り値がtrueであればtrueを返す
if GIDSignIn.sharedInstance()!.handle(url) {
return true
}
return false
}
// ...省略
}
「ViewController.Swift」を編集
次にViewControllerに実装を追加していきます。
import UIKit
import GoogleSignIn
import GoogleAPIClientForREST
import GTMSessionFetcher
class ViewController: UIViewController {
// Google認証系
let googleDriveService = GTLRDriveService()
var googleUser: GIDGoogleUser?
override func viewDidLoad() {
super.viewDidLoad()
// デリゲートを設定
GIDSignIn.sharedInstance()?.delegate = self
// ログイン画面の表示元を設定
GIDSignIn.sharedInstance()?.presentingViewController = self
if let user = GIDSignIn.sharedInstance()?.currentUser {
print("currentUser.profile.email: \(user.profile!.email!)")
} else {
// 次回起動時にはこちらのログが出力される
print("currentUser is nil")
}
}
// GoogleriveLoginボタンアクション
@IBAction func GoogleLogin(_ sender: Any) {
// スコープの追加
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/drive")
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/drive.file")
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/drive.appdata")
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/drive.scripts")
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/drive.metadata")
// ログインを実行
if GIDSignIn.sharedInstance()!.hasPreviousSignIn() {
// 以前のログイン情報が残っていたら復元する
GIDSignIn.sharedInstance()!.restorePreviousSignIn()
} else {
// 通常のログインを実行
GIDSignIn.sharedInstance()?.signIn()
}
return
}
// ファイル取得ボタンアクション
@IBAction func UploadFile(_ sender: Any) {
// メタデータセット
let metadata = GTLRDrive_File.init()
metadata.name = fileName
metadata.mimeType = "image/png"
// 指定フォルダにアップロードする場合
//metadata.parents = ["フォルダID"]
// UIイメージをデータ化
let uploadData:Data? = uploadImage.pngData()!
print("送信データ: \(uploadData!.count) bytes")
// 転送データセット
let uploadParameters = GTLRUploadParameters(data: uploadData! , mimeType:"image/png")
uploadParameters.shouldUploadWithSingleRequest = true
// クエリ
let query = GTLRDriveQuery_FilesCreate.query(withObject: metadata, uploadParameters: uploadParameters)
// クエリ実行
googleDriveService.executeQuery(query, completionHandler: { (ticket: GTLRServiceTicket?, updatedFile: Any?, error: Error?) -> Void in
if error != nil {
print("成功")
} else {
print("失敗")
}
return
})
}
}
// GIDSignInDelegate部分
extension ViewController: GIDSignInDelegate {
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if error == nil {
// ログイン成功した場合
print("signIned user email: \(user!.profile!.email!)")
let service = GTLRDriveService()
service.authorizer = user.authentication.fetcherAuthorizer()
googleUser = user
} else {
// ログイン失敗した場合
print("error: \(error!.localizedDescription)")
}
}
}
上記コードで基本的にボタンなどに関数を紐づければ関数は動くと思います。順番に解説していきます。
// Google認証系
let googleDriveService = GTLRDriveService()
var googleUser: GIDGoogleUser?
override func viewDidLoad() {
super.viewDidLoad()
// デリゲートを設定
GIDSignIn.sharedInstance()?.delegate = self
// ログイン画面の表示元を設定
GIDSignIn.sharedInstance()?.presentingViewController = self
if let user = GIDSignIn.sharedInstance()?.currentUser {
print("currentUser.profile.email: \(user.profile!.email!)")
} else {
// 次回起動時にはこちらのログが出力される
print("currentUser is nil")
}
}
上記の「viewdidload」にdelegate等の設定を行います。if文以下に関しては次回ログイン時にログイン保持されている場合はそのログインを使用するような設定です。
初期画面ではログインされていないのでログインをする必要があります。下記がログイン実行のコードです。
// GoogleriveLoginボタンアクション
@IBAction func GoogleLogin(_ sender: Any) {
// スコープの追加
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/drive")
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/drive.file")
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/drive.appdata")
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/drive.scripts")
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/drive.metadata")
// ログインを実行
if GIDSignIn.sharedInstance()!.hasPreviousSignIn() {
// 以前のログイン情報が残っていたら復元する
GIDSignIn.sharedInstance()!.restorePreviousSignIn()
} else {
// 通常のログインを実行
GIDSignIn.sharedInstance()?.signIn()
}
return
}
よくある記事では下記の部分がなく認証エラーになります。エラー出ている方は原因等を解説した記事もあるので原因等気になる方はこちら参照ください。
// スコープの追加
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/drive")
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/drive.file")
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/drive.appdata")
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/drive.scripts")
GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/drive.metadata")
このログインボタンが押される
拡張に記載したdelegateが走ります。
// GIDSignInDelegate部分
extension ViewController: GIDSignInDelegate {
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if error == nil {
// ログイン成功した場合
print("signIned user email: \(user!.profile!.email!)")
let service = GTLRDriveService()
service.authorizer = user.authentication.fetcherAuthorizer()
googleUser = user
} else {
// ログイン失敗した場合
print("error: \(error!.localizedDescription)")
}
}
}
これでよく見るブラウザベースのGoogleログイン画面が出てくるのでログインすることで認証完了です。どのような権限を与えるかの設定を行い、アプリに戻ります。
ここでコンソールにログインメールアドレスが出力されれば認証成功してGoogleDriveにログインできている状況です。
最後にファイルをアップロードするコードは下記になります。
// ファイル取得ボタンアクション
@IBAction func UploadFile(_ sender: Any) {
// メタデータセット
let metadata = GTLRDrive_File.init()
metadata.name = fileName
metadata.mimeType = "image/png"
// 指定フォルダにアップロードする場合
//metadata.parents = ["フォルダID"]
// UIイメージをデータ化
let uploadData:Data? = uploadImage.pngData()!
print("送信データ: \(uploadData!.count) bytes")
// 転送データセット
let uploadParameters = GTLRUploadParameters(data: uploadData! , mimeType:"image/png")
uploadParameters.shouldUploadWithSingleRequest = true
// クエリ
let query = GTLRDriveQuery_FilesCreate.query(withObject: metadata, uploadParameters: uploadParameters)
// クエリ実行
googleDriveService.executeQuery(query, completionHandler: { (ticket: GTLRServiceTicket?, updatedFile: Any?, error: Error?) -> Void in
if error != nil {
print("成功")
} else {
print("失敗")
}
return
})
}
メタデータセットの部分でメタデータにフォルダIDを設定すると指定のフォルダにファイルを転送できます。その方法に関してはまた別記事で記載するのでそちらを参照ください。
では今回の記事は以上です。他にもSwiftでGoogleDriveAPIを操作する方法に関して記載していくので是非参考にしてみて下さい。
コメント