iOS里很简单的推送,移动端。

来源:互联网 发布:防止网络诈骗手抄报 编辑:程序博客网 时间:2024/06/16 05:31

Apple公司里的推送相比安卓真的很简单,因为系统已经完全通过ASPN实现好了。废话不多具体代码:

iOS 实现推送要实现三段代码。

第一段:在AppDelegate里的,

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

// 获取系统版本号

    double version = [[UIDevicecurrentDevice].systemVersiondoubleValue];//判定系统版本。

    

    if(version>=8.0f){

        UIUserNotificationSettings *settings = [UIUserNotificationSettingssettingsForTypes:(UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert)categories:nil];

        [[UIApplicationsharedApplication] registerUserNotificationSettings:settings];

        [application registerForRemoteNotifications];

    }else{

        UIRemoteNotificationType myTypes =UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert |UIRemoteNotificationTypeSound;

        [[UIApplicationsharedApplication] registerForRemoteNotificationTypes:myTypes];

    }

}

将这段代码粘贴过去就OK了。

第二段:给AppDelegate添加两个方法,

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    

    NSString *token = [NSStringstringWithFormat:@"%@", deviceToken];

    

    token = [token stringByReplacingOccurrencesOfString:@"<"withString:@""];

    token = [token stringByReplacingOccurrencesOfString:@">"withString:@""];

    token = [token stringByReplacingOccurrencesOfString:@" "withString:@""];

    

    //保存token到用户默认设置中

    NSUserDefaults *userDefault =[NSUserDefaultsstandardUserDefaults] ;

    [userDefault setValue:token forKey:@"gjxq_token"];

}


- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

    

}

当你的应用收到苹果返回的Token,会调用第一个方法;如果失败,则会调用第二个方法。


0 0
原创粉丝点击