OK,今天我們來對接一下分享文件到Google Drive。
從網上扒拉扒拉半天,然后看,嗯,大概知道怎么回事,開始搞吧。
首先pod導入:
pod 'GoogleAPIClientForREST/Drive'
pod 'GoogleSignIn'
然后好像還需要引入一個GoogleService-Info.plist文件,當然,這個文件在之前接入firebase統計的時候就已經有了,然后和我們的運營一起找了半天怎么將他們給關聯起來??
隨后在平臺上看到有說,需要打開開關,打開后果然OK,具體位置當時沒有記錄,如有遇到可以之后補充。
然后就是配置文件里進行URL types里添加Scheme,對應的則是GoogleService-Info.plist文件中的REVERSED_CLIENT_ID字段的值。
info文件中配置.png
OK,開始最喜歡的代碼環節。
//導入頭文件
#import <GTLRDrive.h>
#import <GTLRService.h>
#import <GoogleSignIn/GoogleSignIn.h>
共享開始
/// Google Drive
- (void)googleDriveAction {
// 數據初始化
self.googleDriveService = [GTLRDriveService new];
[self googleLogin];
}
登錄調用。我這里不知道為何有些信息不能直接從配置文件中讀取,因此自己手動進行了設置,實際開發根據實際情況處理。
// 1. 登錄
- (void)googleLogin {
// 如果沒有登錄,則去登錄
if ([GIDSignIn sharedInstance].currentUser == nil) {
GIDSignIn.sharedInstance.delegate = self;
GIDSignIn.sharedInstance.scopes = @[kGTLRAuthScopeDrive];
// 因為不能正常讀取GoogleService文件中的屬性,因此手動設置
GIDSignIn.sharedInstance.clientID = @"19603075583-d8eutqdn957od7veesggt4d1morkpuak.apps.googleusercontent.com";
GIDSignIn.sharedInstance.presentingViewController = self;
[GIDSignIn.sharedInstance signIn];
}else {
[self uploadFile:[[NSBundle mainBundle] pathForResource:@"4" ofType:@"pdf"] isImage:NO];
}
}
實現登錄代理
// 實現代理
@interface ShareViewController () <GIDSignInDelegate>
- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user withError:(NSError *)error {
if (error == nil) {
self.googleDriveService.authorizer = user.authentication.fetcherAuthorizer;
self.googleUser = user;
[self uploadFile:[[NSBundle mainBundle] pathForResource:@"4" ofType:@"pdf"] isImage:NO];
}else {
self.googleDriveService.authorizer = nil;
self.googleUser = nil;
}
}
上傳文件
- (void)uploadFile:(NSString *)filePath isImage:(BOOL)isImage {
if (!filePath || ![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSLog(@"file not exist");
return;
}
// 4M 以內
NSData *fileData = [[NSFileManager defaultManager] contentsAtPath:filePath];
GTLRDrive_File *metadata = [GTLRDrive_File object];
metadata.name = isImage?@"4.jpeg":@"4.pdf";
GTLRUploadParameters *uploadParameters = [GTLRUploadParameters uploadParametersWithData:fileData MIMEType:isImage?@"image/jpeg":@"application/pdf"];
uploadParameters.shouldUploadWithSingleRequest = TRUE;
GTLRDriveQuery_FilesCreate *query = [GTLRDriveQuery_FilesCreate queryWithObject:metadata
uploadParameters:uploadParameters];
query.fields = @"id";
GTLRService *driveService = [[GTLRService alloc] init];
driveService.APIKey = @"AIzaSyBbmukUdjQaU-mMf5IvwY7Hjx10q0kqKFU";
driveService.rootURLString = @"https://www.googleapis.com/upload/drive/v3/";
driveService.authorizer = self.googleDriveService.authorizer;
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
GTLRDrive_File *file,
NSError *error) {
if (error == nil) {
NSLog(@"File ID %@", file.identifier);
} else {
NSLog(@"An error occurred: %@", error);
}
}];
}
OK,到這里就結束了,文件共享成功。