How to implement Vision API with 'Service account' in the iOS app?

北城以北 提交于 2020-04-18 06:50:27

问题


I'm trying to implement Google Vision API for the my app via REST. https://cloud.google.com/vision/docs/pdf

Is there any examples or any suggestions how to do this?

Documentation says that they require service account token but can't find any examples how to get service account token from iOS app side. I've tried via GTMAppAuth but getting 403 error

I was able to generate this token from my mac machine and all worked, but token has limited life time and after 3-4 hours it expiries


回答1:


I figured out and did this by my own. Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount#jwt-auth

1)You need to create service account, download p12 or JSON file. JSON file contains private key and public certificate url. You need to create text file, where private key on the top, certificate on the bottom and run this command: openssl pkcs12 -export -in file_name.txt -out file_name.p12

2)Create jwt token with parameters which described in the documentation (for jwt I used this library: https://github.com/yourkarma/JWT)

3) Make POST request to https://www.googleapis.com/oauth2/v4/token with parameters which described in the documentation

Hope it will help somebody in the future




回答2:


First you need to get a Bearer Token... You can get it by following the instructions on this page...

https://cloud.google.com/vision/docs/auth#using_an_api_key

The Bearer Token will not expire, you can implemented it to your code...

A Basic Version on how to add a Bearer Token to your Request in Swift is Shown below... All other Stuff goes as a JSON in Data Format to the "body" parameter

This Link will show you how to build up the JSON for your request to Vision... https://cloud.google.com/vision/docs/using-curl

class APIHandler {

    private let API_TOKEN = "Your Token"

    func requestVisionFromREST(body: Data, completion: @escaping (_ response: Data?)-> Void)  {
        let config = URLSessionConfiguration.default

        var headers = [String:String]()
        headers["Authorization"] = "Bearer \(API_TOKEN)"
        config.httpAdditionalHeaders = headers

        var urlRequest = URLRequest(url: URL(string: "YOUR URL")!)
        urlRequest.httpMethod = "POST"
        urlRequest.httpBody = body

        URLSession(configuration: config).dataTask(with: urlRequest) { (data, response, error) in
            completion(data)
        }.resume()
    }

}

EDIT

If you want to use the Google Sign In instead of the OAuth Method, to reauth your apps and get a fresh token, you can follow the instructions on the googles instructions page below:

https://developers.google.com/identity/sign-in/ios/offline-access



来源:https://stackoverflow.com/questions/53931530/how-to-implement-vision-api-with-service-account-in-the-ios-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!