84
83

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Objective-CでJSON取得して表示する方法

Posted at

条件

今回は適当に東京電力電力供給状況APIからJSON形式で当日の「供給可能最大電力」と現在の「消費電力」を表示する。

-東京電力電力供給状況APIを利用
-日時を取得し2時間前の消費電力を取得する
-西暦、月、日、時間をそれぞれ取得
-json形式で取得する

手順

日付を取得して西暦、月、日、時間をそれぞれ取得

//現在の日付を取得
NSDate *now = [NSDate date];

//NSCalendarでフォーマット
NSCalendar *calendar = [NSCalendar currentCalendar];

NSUInteger flags;
NSDateComponents *comps;
//西暦、月、日、時間をそれぞれ取得
flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit ;
comps = [calendar components:flags fromDate:now];

西暦、月、日、時間をそれぞれ変数に代入

NSInteger year = comps.year;
NSInteger month = comps.month;
NSInteger day = comps.day;
//2時間前を取得する為-2する
NSInteger hour = comps.hour - 2;

東京電力のAPI取得URLを生成

//元のURL
NSString *orign = @"http://tepco-usage-api.appspot.com";
//http://tepco-usage-api.appspot.com/西暦/月/日/時間.jsonとなるように生成
NSString *url = [NSString stringWithFormat:@"%@/%ld/%ld/%ld/%ld.json",orign,year,month,day,hour];

NSURLRequestの生成

//NSURLからNSURLRequestを作る
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
//サーバーとの通信を行う
NSData *json = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//JSONをパース
NSArray *array = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingAllowFragments error:nil];

NSLogで表示

NSLog(@"供給可能最大電力:%@万kW 消費電力:%@万kW", [array valueForKeyPath:@"capacity"], [array valueForKeyPath:@"usage"]);

完成系

NSDate *now = [NSDate date];
    
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger flags;
NSDateComponents *comps;
    
flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit ;
comps = [calendar components:flags fromDate:now];
    
NSInteger year = comps.year;
NSInteger month = comps.month;
NSInteger day = comps.day;
NSInteger hour = comps.hour - 2;
    
NSString *orign = @"http://tepco-usage-api.appspot.com";
NSString *url = [NSString stringWithFormat:@"%@/%ld/%ld/%ld/%ld.json",orign,year,month,day,hour];
    
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSData *json = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSArray *array = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingAllowFragments error:nil];
NSLog(@"供給可能最大電力:%@万kW 消費電力:%@万kW", [array valueForKeyPath:@"capacity"], [array valueForKeyPath:@"usage"]);
84
83
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
84
83

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?