效果展示.gif
一、問題描述
程序啟動的時候會請求用戶是否打開推送,如果打開則能收到推送的新聞內容,相應的功能按鈕也將打開,如果沒有打開用戶可以在更多設置里去手動打開,在我們的程序中并沒有通過打開和關閉按鈕去打開推送,而是讓用戶跳到系統的設置頁面去自己選擇是否打開。
1>設置開關狀態值
// 設置開關狀態
self.switchView.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"push"];
2>判斷是否打開推送
/**
* 判斷是否打開推送
*/
+ (BOOL)isAllowedNotification {
// iOS8 check if user allow notification
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
// system is iOS8
UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
if (UIUserNotificationTypeNone != setting.types) {
return YES;
}
} else {
//iOS7
UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if(UIRemoteNotificationTypeNone != type)
return YES;
}
return NO;
}
3>跳轉到APP的系統設置界面
// 跳轉到APP的系統設置界面
if (switchView.isOn) {
NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if([[UIApplication sharedApplication] canOpenURL:url]) {
NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:url];
}
}
二、解決思路
一開始對于這個功能一點也沒有具體的解決思路,而且一直在程序里去思考這個問題,當用戶跳到系統設置界面以后不管打開沒有打開再次進入到程序中時沒法知道是否打開也沒法更新數據,之后突然想到當跳到系統設置界面的時候,程序已經進入了后臺,自此有了我的解決方案。
1>當用戶跳轉到系統設置界面以后程序進入了后臺,而當再次進入時程序由后臺進入到前臺復原狀態,由此我們可以在applicationDidBecomeActive時發送一個通知。
/**
當程序進入后臺,再返回時注冊發送通知
*/
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// 發送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"pushNoti" object:nil];
}
#######2>之后再需要更新數據的控制器里注冊通知,當收到通知時重新判斷是否打開了推送,然后更新數據。
/**
* 在viewDidLoad里注冊通知
*/
- (void)viewDidLoad {
[super viewDidLoad];
// 是否打開通知使用NSUserDefaults存儲
[[NSUserDefaults standardUserDefaults] setBool:[WEFileUtils isAllowedNotification] forKey:@"push"];
// 注冊通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updataPush) name:@"pushNoti" object:nil];
}
/**
* 收到通知以后重新取值存儲然后更新數據
*/
- (void)updataPush{
[[NSUserDefaults standardUserDefaults] setBool:[WEFileUtils isAllowedNotification] forKey:@"push"];
[self.tableView reloadData];
}
三、結束語
自此應用內打開推送功能集成成功,當然目前新聞推送目前還沒有完美的方案去推送數據,同時只是個人的一些思路和解決方案,寫的不足之處還望海涵,如果可以希望能夠提出一起討論交流。