iOS load UIWebView URL from notification - ios

I'm having a strange issue, using Xcode 5 and testing on iOS 7, I'm sending an extra parameter with the apn request named "url", I need to open that URL in the webview when the notification is received, but the app freeze when the notification arrives if it was connected to the USB, or does nothing when is not connected.
AppDelegate.m
#import "AppDelegate.h"
#implementation AppDelegate
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"Did Register for Remote Notifications with Device Token (%#)", deviceToken);
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"Did Fail to Register for Remote Notifications");
NSLog(#"%#, %#", error, error.localizedDescription);
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Register for Remote Notifications
[application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
if (launchOptions != nil) {
// Launched from push notification
NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
NSLog(#"Notification received");
[self application:application didReceiveRemoteNotification:(NSDictionary*)notification];
}
return YES;
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
if (application.applicationState == UIApplicationStateActive) {
// app was already in the foreground
NSLog(#"app was already in the foreground");
} else {
// app was just brought from background to foreground
NSLog(#"app was just brought from background to foreground");
}
if ([userInfo objectForKey:#"url"])
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"loadNotificationUrl" object:self userInfo:userInfo];
}
}
And that's what is in the ViewerController.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urlString = #"http://example.com/?action=home";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
webView.delegate = self;
webView.opaque = NO;
webView=[[UIWebView alloc]init];
[webView setBackgroundColor:[UIColor grayColor]];
[webView setDelegate:(id<UIWebViewDelegate>)self];
[self.view addSubview:webView];
activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.frame = CGRectMake(200.0, 200.0, 100.0, 40.0);
activityIndicator.center = self.view.center;
[self.view addSubview: activityIndicator];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(loadNotificationUrl:)
name:#"loadNotificationUrl" object:nil];
}
-(void)loadNotificationUrl:(NSNotification*) notification
{
NSDictionary* userInfo = notification.userInfo;
NSString* NotificationUrl = (NSString*)userInfo[#"url"];
NSLog (#"Successfully received: %#", NotificationUrl);
NSURL *url = [NSURL URLWithString:NotificationUrl];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
}
As my little experience, this should load the URL when the notification is clicked, but it is either freeze or does nothing, can anybody tell me where is my mistake please?

Related

Push Notification Using Api

I am working on push notifications,i have an api for push notifications but i don't no how to implement the code.i am using the ios 10 version,please help me.
You can get full idea about implementating Push notification in iOS 10 from below link. Here you will also find steps to implement the same in XCode 8. Please refer below link: Push notification issue with iOS 10
If we use IOS 10 we need to add new frame work and some code
STEP : 1
From iOS 10, we must add UserNotifications framework and delegat.First add this.
STEP : 2
Add the delegate UNUserNotificationCenterDelegate
Now appDelegate.h
#import <UserNotifications/UserNotifications.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>
appDelegate.m
STEP : 3
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
application.applicationIconBadgeNumber = 0;
if( SYSTEM_VERSION_LESS_THAN( #"10.0" ) )
{
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error)
{
if( !error )
{
[[UIApplication sharedApplication] registerForRemoteNotifications]; // required to get the app to do anything at all about push notifications
NSLog( #"Push registration success." );
}
else
{
NSLog( #"Push registration FAILED" );
NSLog( #"ERROR: %# - %#", error.localizedFailureReason, error.localizedDescription );
NSLog( #"SUGGESTIONS: %# - %#", error.localizedRecoveryOptions, error.localizedRecoverySuggestion );
}
}];
}
return YES;
}
STEP : 4
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
// custom stuff we do to register the device with our AWS middleman
NSString *strToken = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#"<>"]];
strToken = [strToken stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"content---%#", strToken);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",#"your url here"]]];
[request setHTTPMethod:#"POST"];
//Pass The String to server
NSString *userUpdate =[NSString stringWithFormat:#"device_token=%#",strToken,nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
if(httpResponse.statusCode == 200)
{
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"The response is - %#",responseDictionary);
}
else
{
NSLog(#"Error");
}
}
else
{
NSLog(#"faield to connect");
}
}];
[dataTask resume];
}
STEP : 5
-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void
(^)(UIBackgroundFetchResult))completionHandler
{
// iOS 10 will handle notifications through other methods
if( SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO( #"10.0" ) )
{
NSLog( #"iOS version >= 10. Let NotificationCenter handle this one." );
// set a member variable to tell the new delegate that this is background
return;
}
NSLog( #"HANDLE PUSH, didReceiveRemoteNotification: %#", userInfo );
// custom code to handle notification content
if( [UIApplication sharedApplication].applicationState == UIApplicationStateInactive )
{
NSLog( #"INACTIVE" );
completionHandler( UIBackgroundFetchResultNewData );
}
else if( [UIApplication sharedApplication].applicationState == UIApplicationStateBackground )
{
NSLog( #"BACKGROUND" );
completionHandler( UIBackgroundFetchResultNewData );
}
else
{
NSLog( #"FOREGROUND" );
completionHandler( UIBackgroundFetchResultNewData );
}
}
//OR
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
[self application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:^(UIBackgroundFetchResult result) {
}];
NSLog(#"Received notification: %#", userInfo);
if ([userInfo count]!=0)
{
NSMutableArray *notify=[[NSMutableArray alloc]init];
NSMutableArray *mutableRetrievedDictionary;
mutableRetrievedDictionary = [[NSUserDefaults standardUserDefaults] objectForKey:#"noyificationcount"] ;
NSMutableArray *deviealert = [[NSUserDefaults standardUserDefaults] objectForKey:#"noyificationcount"] ;
deviealert=[[NSMutableArray alloc]init];
[notify addObject: [[userInfo valueForKey:#"aps"] valueForKey:#"alert"]];
NSLog(#"notification is - %#", notify);
NSString *strAlertValue = [[userInfo valueForKey:#"aps"] valueForKey:#"badge"];
NSLog(#"my message-- %#",strAlertValue);
deviealert=[notify mutableCopy];
NSLog(#"new...%#",deviealert);
[[ NSUserDefaults standardUserDefaults]setObject:deviealert forKey:#"noyificationcount" ];
[[NSUserDefaults standardUserDefaults]synchronize];
NSLog(#"dev.....%#",deviealert);
[UIApplication sharedApplication].applicationIconBadgeNumber+=1;
}
}
STEP : 6
For Foreground State
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
NSLog( #"Handle push from foreground" );
// custom code to handle push while app is in the foreground
NSLog(#"%#", notification.request.content.userInfo);
}
STEP : 7
For Background State
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)())completionHandler
{
NSLog( #"Handle push from background or closed" );
// if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background
NSLog(#"%#", response.notification.request.content.userInfo);
//Adding notification here
[[NSNotificationCenter defaultCenter] postNotificationName:#"reloadTheTable" object:nil];
}

Maps not being shown in webview- iOS

I have a button in my view. On clicking it leads to a webview in which I want to show the maps. The code I am using is:
- (void)viewWillAppear:(BOOL)animated{
NSString *url = [#"http://maps.apple.com/?q=" stringByAppendingString:self.address];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
NSURLRequest *metricsRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
_webViewForLocation.delegate = self;
[_webViewForLocation loadRequest:metricsRequest];
NSLog(#"Maps String: %#", url);
}
But the webview is blank. HOw do I show maps in it?
try
- (void)viewDidLoad
{
[super viewDidLoad];
[_webViewForLocation loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://maps.google.com/?q=bangalore"]]]]; // here pass your string
- (void)webViewDidStartLoad:(UIWebView *)webView
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
the output is
refers this document,

How to register a device in ios

i am developing a app and whenever my app is installed on a iDevice, i must register that device, in the server through a post Web service, how to do that, This is what so far i have done:
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if ([application respondsToSelector:#selector(isRegisteredForRemoteNotifications)])
{
// iOS 8 Notifications
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[application registerForRemoteNotifications];
}
else
{
// iOS < 8 Notifications
//[application registerForRemoteNotificationTypes:
// (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
}
return YES;
}
and then i wrote the following,
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *devToken = [[[[deviceToken description]
stringByReplacingOccurrencesOfString:#"<"withString:#""]
stringByReplacingOccurrencesOfString:#">" withString:#""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
[self registerDeviceTokenWithServer:devToken];
}
Next this method
-(void)registerDeviceTokenWithServer :(NSString*)deviceToken{
[NSThread detachNewThreadSelector:#selector(registerDeviceInBackground:)
toTarget:self withObject:deviceToken];
}
and now i need to register the mobile through the device token in the following method through a post call Web service, how to do that,
-(void)registerDeviceInBackground :(NSString*)deviceToken
{
I need to write the code here a post call method.
}
If any code help is there, is well appreciated.
You can write this:
-(void)registerDeviceTokenWithServer :(NSString*)deviceToken{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSURL *s = [NSURL URLWithString: #"www.apple.com/yoururl"];
NSMutableURLRequest *requestURL = [NSMutableURLRequest requestWithURL:s cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:90.00];
[requestURL setHTTPMethod:#"POST"];
NSError *error = [[NSError alloc] init];
if ([parameter isKindOfClass : [NSString class]]) {
[requestURL setHTTPBody:[devToken dataUsingEncoding:NSUTF8StringEncoding]];
}
NSHTTPURLResponse *response;
NSError *error1;
NSData *apiData = [NSURLConnection sendSynchronousRequest:requestURL returningResponse:&response error:&error1];
dictionaryData = [NSJSONSerialization JSONObjectWithData:apiData options:kNilOptions error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
if ([[dictionaryData objectForKey:#"status"] isEqualToString:#"success"]) {
//Post successful
}
else if([[apiDataBack objectForKey:#"status"] isEqualToString:#"error"]){
//error
}
});
});
}
Above code will post the device token asynchronously.
Hope this helps.. :)

Push Notification View the Particular View Controller by Tapping on Notification IOS7

Hi in my application i have the push notification when user tap the notification its going to the main view controller i to view a particular view controller by tapping on the notification i have tried some methods its not working for me so please tell to make it done.
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
const char* data = [deviceToken bytes];
NSMutableString * token = [NSMutableString string];
for (int i = 0; i < [deviceToken length]; i++) {
[token appendFormat:#"%02.2hhX", data[i]];
}
NSString *urlString = [NSString stringWithFormat:#"url?token=%#",token];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSLog(#"token %#",urlString);
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSLog(#"request %# ",urlRequest);
NSData *urlData;
NSURLResponse *response;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil];
NSLog(#"data %#",urlData);
[self clearNotifications];
}
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[[UIApplication sharedApplication] cancelLocalNotification:notification];
//My_specificViewController
updatepoliticalViewController *ringingVC = [self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:#"updatepoliticalViewController"];
[self.window setRootViewController:ringingVC];
}
Tthe above i have tried its not working for please tell where I'm doing worng what is the correct way to make it done.
Thanks.
Try like this
Dont set as rootviewcontroller
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
updatepoliticalViewController *ringingVC = [self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:#"updatepoliticalViewController"];
[self.navigationController pushViewController:ringingVC animated:YES];
}

How to show Push notification as image

i am working on one application in which server will send me image in base64 as a push notification format as and from ios side i have to display this image with decode of base 64?I can do decoding and all but how i will display PNS as image
Is it possible to accept PNS as image(in base64)?
Code i am using as below,
#pragma mark -
#pragma mark - Push Notifications Methods
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *tokenStr = [deviceToken description];
// Separete Your device token with <,< and blanksapace
NSString *pushToken = [[[tokenStr
stringByReplacingOccurrencesOfString:#"<" withString:#""]
stringByReplacingOccurrencesOfString:#">" withString:#""]
stringByReplacingOccurrencesOfString:#" " withString:#""];
// Save the token to server
NSString *urlStr = [NSString stringWithFormat:#"http://www.vijaywebsolutions.com/Development_FTP/webservice/webservices.php?deviceToken=%#",pushToken]; // Passing token to URL
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self]; // Support to perform URLrequest
if( theConnection )// checking connection successfull or not
{
webData = [NSMutableData data];
NSLog(#"device token is %#", pushToken);
}
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
if (application.applicationState == UIApplicationStateActive)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Did receive a Remote Notification" message:[NSString stringWithFormat:#"You Have a Notification :\n%#",userInfo[#"aps"][#"alert"]]delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
}
You can't. The notification to the user will present the title and message text and then, if the user triggers the notification to open the app, your app will be passed the full notification data and you can display the image.

Resources