#16 — 飲料訂購APP_Part1|Firebase登入&Imgur API 上傳圖片

註冊登入Firebase,將專案加入Firebase中

依照網站步驟一一設定

利用SPM加入 firebase-ios-sdk ,並且在 AppDelegate.swift裡呼叫 FirebaseApp.configure()

import UIKit
import Firebase
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {

FirebaseApp.configure()

return true
}
}

在Firebase建立的專案Authentication裡選擇Sign-in method新增想要設定的登入系統,這裡先使用Firebase最基本的都入註冊功能,之後會補上我國最常使用的FB、Google登入系統。

實際操作畫面如下

import Firebase後可以呼叫Auth.auth().createUser(withEmail: “設定Email”, password: “設定密碼”)從程式建立帳號密碼

呼叫Auth.auth().currentUser?.createProfileChangeRequest().displayName.photoURL設定使用者名字、照片網址

呼叫Auth.auth().signIn(withEmail: “你的Email”, password: “你的密碼”)來登入帳號

Auth.auth().currentUserAuth.auth().addStateDidChangeListener是否有值判斷使用者是否登入,差別在於後者會申請接收登入狀態改變的通知,當使用者登入 / 登出時就會執行一次closure內設定的程式碼,例如我下圖寫了如果closure 參數 user 有值就執行performSegue,所以我不管登入或註冊都會執行performSegue

由下圖可以看出我並未在註冊Button IBAction內寫任何會執行segue的程式碼

依自己喜好、情況選擇較適合的方式,在這裡我用Auth.auth().currentUser

(如果使用者未登出,下次打開APP使用者還是能保持登入。)

結果:

呼叫Auth.auth().signOut()登出

同樣呼叫Auth.auth().currentUser取得使用者的基本資訊

if let user = Auth.auth().currentUser {
print(user.uid, user.email, user.displayName, user.photoURL)
}

特別的是在Authentication 頁面儲存的使用者資料有限,如果要額外新增欄位或讀取使用者其他資訊就需要利用 Cloud Firestore 實現資料的建立、讀取、修改 & 刪除,可直接參考下方連結。

為了方便利用Auth.auth().currentUser取得.displayName顯示使用者姓名.photoURL顯示使用者圖片網址,但是在此之前就必須把使用者上傳的圖片轉成網址,所以這裡我用了Imgur API上傳並取得網址。

因為我只需要圖片的網址,所以接收回傳自定義型別只定義了 link 欄位

SPM加入Alamofire套件,將上傳的程式碼寫在自定義Function裡,如果成功上傳片,再將回傳的圖片網址存在變數url

var url:URL?//圖片上傳到imgur,在利用回傳讀取圖片網址
func uploadImage(uiImage: UIImage) {
let headers: HTTPHeaders = [
"Authorization": "Client-ID 你的ID",
]
AF.upload(multipartFormData: { data in
let imageData = uiImage.jpegData(compressionQuality: 0.9)
data.append(imageData!, withName: "image")
}, to: "https://api.imgur.com/3/image", headers: headers).responseDecodable(of: ImgurImageResponse.self, queue: .main, decoder: JSONDecoder()) { response in
switch response.result {
case .success(let result):
self.url = result.data.link
print(result.data.link)
case .failure(let error):
print(error)
}
}
}

利用UIImagePickerViewController選取相機、PHPickerViewController選取相簿,在選擇相簿、拍攝照片完同時上傳圖片,得到的圖片網址(變數url)將存取在Auth.auth().currentUser?.createProfileChangeRequest().photoURL裡

--

--