Skip to content

Instantly share code, notes, and snippets.

@TomoyaOnishi
Last active January 3, 2016 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TomoyaOnishi/8505208 to your computer and use it in GitHub Desktop.
Save TomoyaOnishi/8505208 to your computer and use it in GitHub Desktop.
push通知を受け取った時にサーバから情報をダウンロードする
//
// RNAppDelegate.m
// RemoteNotification
//
// Created by TomoyaOnishi on 2014/01/19.
// Copyright (c) 2014年 TomoyaOnishi. All rights reserved.
//
#import "RNAppDelegate.h"
@interface RNAppDelegate ()
- (void)registerRemoteNotification;
@end
@implementation RNAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
// デバイストークンをサーバに送る
}
/*
* content-available:1がついていないpush通知はこのメソッドが呼ばれる(アプリ起動時のみ!)
* でバックグラウンドで起動しない
*/
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
}
/*
* content-available:1がついているpush通知はこのメソッドが呼ばれる
* 30秒間動く時間を与えられる
*/
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
// サーバに情報を取得しにいく
NSString *imageURLString = userInfo[@"image_url"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURLString]];
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:&error];
if (error) {
// 失敗したときに呼ぶ
completionHandler(UIBackgroundFetchResultFailed);
return;
}
// dataが画像でユーザに見せたいとき
UIImage *image = [UIImage imageWithData:data];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[self.window.rootViewController.view addSubview:imageView];
// ユーザに見せるべき有効な情報が取得できた時に呼ぶ(AppSwitcherの画面が再描画され、起動が終了する)
completionHandler(UIBackgroundFetchResultNewData);
}
- (void)registerRemoteNotification
{
// UIRemoteNotificationTypeNewsstandContentAvailabilityを
// つけたほうが良いという情報もあるが不要なものは付けない
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment