Getting NSError domain: “com.google.GTLJSONRPCErro

2019-02-21 02:12发布

问题:

I am trying to fetch Calendar events to my iOS application. So, for that I have create a project in Google developers console and got Client ID, ApiKey.

And installed pods with

pod 'GoogleAPIClient/Calendar', '~> 1.0.2'
pod 'GTMOAuth2', '~> 1.1.0'
pod 'Google/SignIn'

And after signing to Gmail, its asking permission to access Calendar, till that working fine, but, while fetching the events showing following error.

error   NSError domain: "com.google.GTLJSONRPCErrorDomain" - code: 401  0x0000604000646330

And my code is follows

private let scopes = [kGTLAuthScopeCalendar]

private let service = GTLServiceCalendar()

private let kApiKey = "someKey"

let output = UITextView()

private let kKeychainItemName = "Google Calendar API"

private let kClientID = "SomeID"

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {

    if (error == nil) {


    } else {
        print("\(error.localizedDescription)")
    }

    if user != nil {
        output.frame = view.bounds
        output.isEditable = false
        output.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0)
        output.autoresizingMask = [.flexibleHeight, .flexibleWidth]

        view.addSubview(output);

        if let auth = GTMOAuth2ViewControllerTouch.authForGoogleFromKeychain(
            forName: kKeychainItemName,
            clientID: kClientID,
            clientSecret: nil) {
            service.authorizer = auth
        }

        print("\(user)")
        service.authorizer = user.authentication.fetcherAuthorizer()
        fetchEvents()
    }

}

func fetchEvents() {

    let query = GTLQueryCalendar.queryForEventsList(withCalendarId: "primary")

    query?.maxResults = 10
    query?.singleEvents = true
    query?.orderBy = kGTLCalendarOrderByStartTime
    service.executeQuery(
        (query)!,
        delegate: self,
        didFinish: #selector(displayResultWithTicket(ticket:finishedWithObject:error:)))
}

// Display the start dates and event summaries in the UITextView

@objc func displayResultWithTicket(

    ticket: GTLServiceTicket,
    finishedWithObject response : GTLCalendarEvents,
    error : NSError?) {

    if let error = error {
        showAlert(title: "Error", message: error.localizedDescription)
        return
    }

    var eventString = ""

    if let events = response.items(), !events.isEmpty {
        for event in events as! [GTLCalendarEvent] {
            print(event)
        }
    } else {
    print("No upcoming events found.")
  }
}

   func showAlert(title: String, message: String) {

    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "Thank You", style: UIAlertActionStyle.default, handler: nil))
    self.present(alert, animated: true, completion: nil)

    }    

override func viewDidLoad() {
    super.viewDidLoad()

    GIDSignIn.sharedInstance().clientID = kClientID
    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().scopes = scopes
    GIDSignIn.sharedInstance().signIn()
    GIDSignIn.sharedInstance().delegate = self
    service.apiKey = kApiKey
}

Even I checked few forums, I did not get any solution for this.

Can anyone suggest me where I am getting wrong?

回答1:

Swift - 4

I doesn't recognise why you are getting that error. I think you are not using latest pods. Refer following code, that I have used for fetch google calendar events.

Pods: - pod 'GoogleAPIClientForREST/Calendar', '~> 1.2.1'

pod 'Google/SignIn', '~> 3.0.3'

import UIKit
import GoogleAPIClientForREST
import GoogleSignIn
class ClassForCalEvent: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate {

    let eventArray = NSMutableArray()
    private let scopes = [kGTLRAuthScopeCalendar]

    private let service = GTLRCalendarService()
    override func viewDidLoad() {
        super.viewDidLoad()

          // Configure Google Sign-in.
            GIDSignIn.sharedInstance().delegate = self
            GIDSignIn.sharedInstance().uiDelegate = self
            GIDSignIn.sharedInstance().scopes = scopes
            GIDSignIn.sharedInstance().signIn()

    }

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
              withError error: Error!) {
        if let error = error {
            showAlert(title: "Authentication Error", message: error.localizedDescription)
            self.service.authorizer = nil
        } else {
                        self.service.authorizer = user.authentication.fetcherAuthorizer()
            fetchEvents()
        }
    }

    // Construct a query and get a list of upcoming events from the user calendar
    func fetchEvents() {
        let query = GTLRCalendarQuery_EventsList.query(withCalendarId: "primary")
        query.maxResults = 10
        query.timeMin = GTLRDateTime(date: Date())
        query.singleEvents = true
        query.orderBy = kGTLRCalendarOrderByStartTime
        service.executeQuery(
            query,
            delegate: self,
            didFinish: #selector(displayResultWithTicket(ticket:finishedWithObject:error:)))
    }

    // Display the start dates and event summaries in the UITextView
    @objc func displayResultWithTicket(
        ticket: GTLRServiceTicket,
        finishedWithObject response : GTLRCalendar_Events,
        error : NSError?) {

        if let error = error {
            showAlert(title: "Error", message: error.localizedDescription)
            return
        }

        var outputText = ""
        if let events = response.items, !events.isEmpty {
            for event in events {
                let start = event.start!.dateTime ?? event.start!.date!
                let startString = DateFormatter.localizedString(
                    from: start.date,
                    dateStyle: .short,
                    timeStyle: .short)

                let dataDic = ["start_Time":startString , "tag":"red", "Event_Name":event.summary!] 
                eventArray.add(dataDic)

                outputText += "\(startString) - \(event.summary!)\n"
                print("Output ", startString , event )
            }
            UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject: eventArray), forKey: "EventArray")

            UserDefaults.standard.synchronize()
        } else
        {
            outputText = "No upcoming events found."
        }
        print("Output Text",outputText)
        showAlert(title: "Event Sync Succesfully!", message:"")
    }