带有Swift的Google Objective-C API'GTL' [英] Google Objective-C API 'GTL' with Swift

查看:130
本文介绍了带有Swift的Google Objective-C API'GTL'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人设法在Swift Project中使用Google Drive API(Objjective C)

https://developers.google.com/drive/ios/quickstart



我试过很多不同的方式,但无法编译



最接近的是在下面的链接中使用Rob的方法,并将#importGTLDrive.h添加到BridgingHeader 。这允许我创建一个GTLDrive,但不是Auth,因为我无法让Xcode关注No ARC标志。



Stackoverflow 11370752

解决方案

我最终设法通过以下方式来完成这项工作: Stack OverFlow 11370752

并添加一个bridging-header.h文件和

  #importGTLDrive.h
#importGTMOAuth2ViewControllerTouch.h

为了节省时间,我将我的Objective-C包含到Google Quickstart中包含的示例的Swift翻译中。

适用于Google云端硬盘的IOS快速入门

  impo rt UIKit 
导入MobileCoreServices

类ViewController:UIViewController,UINavigationControllerDelegate,UIImagePickerControllerDelegate {
var window:UIWindow?
让driveService:GTLServiceDrive = GTLServiceDrive()

让kKeychainItemName:NSString =Google Drive Quickstart
让kClientID:NSString =您的客户端ID
让kClientSecret :NSString =Your Secret

func showWaitIndicator(title:String) - > UIAlertView {
// println(showWaitIndicator \(title))
var progressAlert = UIAlertView()
progressAlert.title = title
progressAlert.message =Please Wait。 ...
progressAlert.show()

let activityView = UIActivityIndi​​catorView(activityIndi​​catorStyle:UIActivityIndi​​catorViewStyle.White)
activityView.center = CGPointMake(progressAlert.bounds.size.width / 2,progressAlert.bounds.size.height - 45)
progressAlert.addSubview(activityView)
activityView.hidesWhenStopped = true
activityView.startAnimating()
return progressAlert
}
$ b $重写func viewDidLoad(){
super.viewDidLoad()
self.driveService.authorizer = GTMOAuth2ViewControllerTouch.authForGoogleFromKeychainForName(kKeychainItemName,
clientID:kClientID,
clientSecret:kClientSecret)
}

覆盖func viewDidAppear(animated:Bool){
self.showCamera ()


$ b $ func showCamera(){
var cameraUI = UIImagePickerController()
如果UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
cameraUI.sourceType = UIImagePickerControllerSourceType.Camera
} else {
cameraUI.sourceType = UIImagePickerControllerSourceType.PhotoLibrary $ b $ if if UIDevice.currentDevice()。userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
self .showAlert(Error,消息:Ipad Simulator not supported)
return
}
}

cameraUI.mediaTypes = [kUTTypeImage as String]
cameraUI.allowsEditing = true
cameraUI.delegate = self
self.presentModalViewController(cameraUI,animated:true)
println(Show Camera \(self.isAuthorized()))
if(!self.isAuthorized())
{
//尚未授权,请求授权并将登录UI推入naviga重叠堆栈。
cameraUI.pushViewController(self.createAuthController(),animated:true);


//处理图像的选择
func imagePickerController(picker:UIImagePickerController,didFinishPickingMediaWithInfo info:NSDictionary){
println(imagePickerController didFinishPickingMediaWithInfo)
让image = info.valueForKey(UIImagePickerControllerOriginalImage)作为UIImage
self.dismissModalViewControllerAnimated(true)
self.uploadPhoto(image)



//从图像选择器/相机处理取消。

func imagePickerControllerDidCancel(picker:UIImagePickerController){
self.dismissModalViewControllerAnimated(true)
}

//助手检查用户是否被授权
func isAuthorized() - > Bool {
return(self.driveService.authorizer as GTMOAuth2Authentication).canAuthorize
}

//创建用于授权访问Google Drive的授权控制器。
func createAuthController() - > GTMOAuth2ViewControllerTouch {
return GTMOAuth2ViewControllerTouch(范围:kGTLAuthScopeDriveFile,
clientID:kClientID,
clientSecret:kClientSecret,
keychainItemName:kKeychainItemName,
delegate:self,
finishedSelector :Selector(viewController:finishedWithAuth:error:))


//func join(string s1:String,toString s2:String,withJoiner joiner:String)

//处理完成授权过程,并使用新凭据更新Drive service
//。
func viewController(viewController:GTMOAuth2ViewControllerTouch,finishedWithAuth authResult:GTMOAuth2Authentication,error:NSError){
if error!= nil
{
self.showAlert(Authentication Error,message: error.localizedDescription)
self.driveService.authorizer = nil
} else {
println(Authentication success)
self.driveService.authorizer = authResult
}



$ b //将照片上传到Google云端硬盘
func uploadPhoto(image:UIImage){
println(上传照片 )
let dateFormat = NSDateFormatter()
dateFormat.dateFormat ='快速启动上传的文件('EEEE MMMM d,YYYY h:mm a,zzz')

让文件= GTLDriveFile.object()as GTLDriveFile
file.title = dateFormat.stringFromDate(NSDate())
file.descriptionProperty =从Google Drive IOS上传
file.mimeType =image / png

让data = UIImagePNGR epresentation(image)
let uploadParameters = GTLUploadParameters(data:data,MIMEType:file.mimeType)
let query = GTLQueryDrive.queryForFilesInsertWithObject(file,uploadParameters:uploadParameters)as GTLQueryDrive
let waitIndicator = self .showWaitIndicator(上传到Google Drive)
// {
// $ b中的self.driveService.executeQuery(query,completionHandler:{(ticket:GTLServiceTicket,insertedFile:AnyObject,error:NSError) $ b //
//}
// elf.driveService.executeQuery(< #query:GTLQueryProtocol?#> ;, completionHandler:<#((GTLServiceTicket !, AnyObject !, NSError!) - > Void)?#>)
self.driveService.executeQuery(query,completionHandler:{(ticket,insertedFile,error) - >无效
let myFile = insertedFile as?GTLDriveFile

waitIndicator.dismissWithClickedButtonIndex(0,animated:true)
if error == nil {
println(File ID \(myFile?.identifier))
self.showAlert Google Drive,信息:保存文件)
} else {
println(发生错误!\(错误))
self.showAlert(Google Drive,消息:对不起,发生了错误!)
}

})
}

func showAlert(title:String,message:String) {
let cancel =OK
println(show Alert)
let alert = UIAlertView()
alert.title = title
alert.message = message
alert.addButtonWithTitle(取消)
alert.show()
}

}


Has anyone managed to use the Google Drive Api (Objjective C) in a Swift Project

https://developers.google.com/drive/ios/quickstart

I have tried a number of different ways but cannot get it to compile

The closest I came was using Rob's methodology in the link below and adding #import "GTLDrive.h" to the BridgingHeader. This allowed me to create a GTLDrive but not the Auth becauser I could not get Xcode to pay attention to the No ARC flags.

Stackoverflow 11370752

解决方案

I eventually managed to do this by following

Stack OverFlow 11370752

and adding a bridging-header.h file with

#import "GTLDrive.h"
#import "GTMOAuth2ViewControllerTouch.h"

To save someone time I include my Objective-C to Swift Translation of the sample included in the Google Quickstart

IOS Quickstart for Google Drive

import UIKit
import MobileCoreServices

class ViewController: UIViewController , UINavigationControllerDelegate ,UIImagePickerControllerDelegate {
var window: UIWindow?
let driveService : GTLServiceDrive =  GTLServiceDrive()

let kKeychainItemName : NSString = "Google Drive Quickstart"
let kClientID : NSString = "Your Client ID"
let kClientSecret : NSString = "Your Secret"

func showWaitIndicator(title:String) -> UIAlertView {
    //        println("showWaitIndicator \(title)")
    var progressAlert = UIAlertView()
    progressAlert.title = title
    progressAlert.message = "Please Wait...."
    progressAlert.show()

    let activityView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
    activityView.center = CGPointMake(progressAlert.bounds.size.width / 2, progressAlert.bounds.size.height - 45)
    progressAlert.addSubview(activityView)
    activityView.hidesWhenStopped = true
    activityView.startAnimating()
    return progressAlert
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.driveService.authorizer  = GTMOAuth2ViewControllerTouch.authForGoogleFromKeychainForName(kKeychainItemName,
        clientID: kClientID,
        clientSecret: kClientSecret)
}

override func viewDidAppear(animated: Bool) {
    self.showCamera()
}


func showCamera() {
    var cameraUI = UIImagePickerController()
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
        cameraUI.sourceType = UIImagePickerControllerSourceType.Camera
    } else {
        cameraUI.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
            self.showAlert("Error", message: "Ipad Simulator not supported")
            return
        }
    }

    cameraUI.mediaTypes = [kUTTypeImage as String]
    cameraUI.allowsEditing = true
    cameraUI.delegate = self
    self.presentModalViewController(cameraUI, animated: true)
    println("Show Camera \(self.isAuthorized())")
    if (!self.isAuthorized())
    {
        // Not yet authorized, request authorization and push the login UI onto the navigation stack.
        cameraUI.pushViewController(self.createAuthController(), animated:true);
    }
}
// Handle selection of an image
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info:NSDictionary) {
    println("imagePickerController didFinishPickingMediaWithInfo")
    let image = info.valueForKey(UIImagePickerControllerOriginalImage) as UIImage
    self.dismissModalViewControllerAnimated(true)
    self.uploadPhoto(image)

}

// Handle cancel from image picker/camera.

func imagePickerControllerDidCancel(picker: UIImagePickerController){
    self.dismissModalViewControllerAnimated(true)
}

// Helper to check if user is authorized
func isAuthorized() -> Bool {
    return (self.driveService.authorizer as GTMOAuth2Authentication).canAuthorize
}

// Creates the auth controller for authorizing access to Google Drive.
func createAuthController() -> GTMOAuth2ViewControllerTouch {
    return GTMOAuth2ViewControllerTouch(scope: kGTLAuthScopeDriveFile,
        clientID: kClientID,
        clientSecret: kClientSecret,
        keychainItemName: kKeychainItemName,
        delegate: self,
        finishedSelector: Selector("viewController:finishedWithAuth:error:"))

}
//     "func join(string s1: String, toString s2: String, withJoiner joiner: String)"

// Handle completion of the authorization process, and updates the Drive service
// with the new credentials.
func viewController(viewController: GTMOAuth2ViewControllerTouch , finishedWithAuth authResult: GTMOAuth2Authentication , error:NSError ) {
    if error != nil
    {
        self.showAlert("Authentication Error", message:error.localizedDescription)
        self.driveService.authorizer = nil
    } else {
        println("Authentication success")
        self.driveService.authorizer = authResult
    }

}


// Uploads a photo to Google Drive
func uploadPhoto(image: UIImage) {
    println("uploading Photo")
    let dateFormat  = NSDateFormatter()
    dateFormat.dateFormat = "'Quickstart Uploaded File ('EEEE MMMM d, YYYY h:mm a, zzz')"

    let file = GTLDriveFile.object() as GTLDriveFile
    file.title = dateFormat.stringFromDate(NSDate())
    file.descriptionProperty = "Uploaded from Google Drive IOS"
    file.mimeType = "image/png"

    let data = UIImagePNGRepresentation(image)
    let uploadParameters = GTLUploadParameters(data: data, MIMEType: file.mimeType)
    let query = GTLQueryDrive.queryForFilesInsertWithObject(file, uploadParameters: uploadParameters) as GTLQueryDrive
    let waitIndicator = self.showWaitIndicator("Uploading To Google Drive")
    //        self.driveService.executeQuery(query, completionHandler: {(ticket: GTLServiceTicket, insertedFile: AnyObject, error: NSError) in {
    //
    //
    //        }
    // elf.driveService.executeQuery(<#query: GTLQueryProtocol?#>, completionHandler: <#((GTLServiceTicket!, AnyObject!, NSError!) -> Void)?#>)
    self.driveService.executeQuery(query, completionHandler:  { (ticket, insertedFile , error) -> Void in
        let myFile = insertedFile as? GTLDriveFile

        waitIndicator.dismissWithClickedButtonIndex(0, animated: true)
        if error == nil {
            println("File ID \(myFile?.identifier)")
            self.showAlert("Google Drive", message: "File Saved")
        } else {
            println("An Error Occurred! \(error)")
            self.showAlert("Google Drive", message: "Sorry, an error occurred!")
        }

        })
}

func showAlert(title: String, message: String ) {
    let cancel = "OK"
    println("show Alert")
    let alert = UIAlertView()
    alert.title = title
    alert.message = message
    alert.addButtonWithTitle(cancel)
    alert.show()
}

}

这篇关于带有Swift的Google Objective-C API'GTL'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆