How to get JSON from google calendar API in swift?

2019-06-13 16:44发布

问题:

What I want to do is sync the data from google calendar to my app.

I can login my app with google+ account now, then how can I get the private JSON data from calendar with my account ID and password?

Thanks in advance.

回答1:

I was able to retrieve JSON data via HTTP requests using Google Calendar API. As an example, here is a code snippet to make a request to retrieve my calendar metadata:

let url = NSURL(string: "https://www.googleapis.com/calendar/v3/calendars/calendarId")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
    let dataAsNSString = NSString(data: data, encoding: NSUTF8StringEncoding)
    // implement your app logic
}
task.resume()

As far as syncing data between your app and Google Calendar, you can implement callbacks to make PUT requests to update via Google Calendar API. As an example, here is a code snippet for a callback function to make a PUT request to sync w/ your Google Calendar:

func updateUserDataToGoogleCalendar(calendarId: String) {
    let url = NSURL(string:"https://www.googleapis.com/calendar/v3/calendars/calendarId")
    let dataAsString = "sync data"
    var data: NSData? = dataAsString.dataUsingEncoding(NSUTF8StringEncoding)
    var headers = Dictionary<String, String>()   // specify any headers

    Http().put(url!, headers: headers, data:data!) { (result) in           
    if result.success {
        if let json: AnyObject = result.jsonObject {
            // implement your app logic
        }
    }
}

There are numerous Swift HTTP wrapper libraries available. In my example, I am using Swift HTTP.