Sample code for 30+ languages & platforms
Objective-C Requires Chilkat v11.0.0+

SendGrid: Report daily requests, deliveries, bounces, and blocks

See more SendGrid Examples

Retrieve seven completed UTC dates and print one row per date. The counts are account-level aggregates; a day’s delivered count does not identify which messages sent that day were delivered.

Global email statistics

Chilkat Objective-C Downloads

Objective-C
#import <CkoHttp.h>
#import <CkoHttpResponse.h>
#import <CkoDateTime.h>
#import <CkoJsonArray.h>
#import <CkoJsonObject.h>

BOOL success = NO;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = NO;
CkoHttp *http = [[CkoHttp alloc] init];
http.RequireSslCertVerify = YES;
//  Supply your API key from protected configuration; AuthToken adds the Bearer prefix.
http.AuthToken = @"SENDGRID_API_KEY";
CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];

CkoDateTime *day = [[CkoDateTime alloc] init];
[day SetFromCurrentSystemTime];
[day AddDays: [NSNumber numberWithInt: -1]];
[http SetUrlVar: @"end" value: [day GetAsIso8601: @"YYYY-MM-DD" bLocal: NO]];
[day AddDays: [NSNumber numberWithInt: -6]];
[http SetUrlVar: @"start" value: [day GetAsIso8601: @"YYYY-MM-DD" bLocal: NO]];

success = [http HttpNoBody: @"GET" url: @"https://api.sendgrid.com/v3/stats?start_date={$start}&end_date={$end}&aggregated_by=day" response: resp];
if (success != YES) {
    if ([resp.StatusCode intValue] == 0) {
        NSLog(@"%@",http.LastErrorText);
    }
    else {
        NSLog(@"%@%d%@%@",@"HTTP ",[resp.StatusCode intValue],@": ",resp.BodyStr);
    }

    return;
}

if ([resp.StatusCode intValue] != 200) {
    NSLog(@"%@%d%@%@",@"HTTP ",[resp.StatusCode intValue],@": ",resp.BodyStr);
    return;
}

CkoJsonArray *days = [[CkoJsonArray alloc] init];
success = [days Load: resp.BodyStr];
if (success != YES) {
    NSLog(@"%@",@"Unexpected response: expected JSON.");
    return;
}

NSLog(@"%@",@"Date,Requests,Delivered,Bounces,Blocks");
CkoJsonObject *row = [[CkoJsonObject alloc] init];
int i = 0;
while ((i < [days.Size intValue])) {
    [days ObjectAt2: [NSNumber numberWithInt: i] jsonObj: row];
    NSLog(@"%@%@%d%@%d%@%d%@%d",[row StringOf: @"date"],@",",[[row IntOf: @"stats[0].metrics.requests"] intValue],@",",[[row IntOf: @"stats[0].metrics.delivered"] intValue]
        ,@",",[[row IntOf: @"stats[0].metrics.bounces"] intValue],@",",[[row IntOf: @"stats[0].metrics.blocks"] intValue]);
    i = i + 1;
}