i want navigate to another file in webview. - ios

i want to call objective c file from javascript.
- (void)viewDidLoad
{
webview.delegate = self;
myButton.enabled = NO;
NSString *path=[[NSBundle mainBundle]pathForResource:#"1" ofType:#"html" inDirectory:#"files"];
NSURL *url=[NSURL fileURLWithPath:path];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[webview loadRequest:request];}
i am using this code to call my html page successfully and i use the below code to call shouldStartLoadWithRequest method in objective c.
<img src="cercle24px.png" />
now i went to call new TestViewController.m file how to i call this file, i used the below code.its print the nslog correctly and give alert box also.but doesn't navigate to next file.please help me if any one know.i am waiting for your valuable reply please.
- (BOOL)webView:(UIWebView*)webview shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(#"what");
UIAlertView *tstAlert = [[UIAlertView alloc] initWithTitle:#"" message:#"Allowed only alphabets and numeric" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[tstAlert show];
NSString *absoluteUrl = [[request URL] absoluteString];
NSLog(#"absolute%#",absoluteUrl);
if ([absoluteUrl isEqualToString:#"didtap://button1"]) {
NSLog(#"yes");
TestViewController *testview=[[TestViewController alloc]initWithNibName:#"TestViewController" bundle:nil];
[self.navigationController pushViewController:testview animated:YES];
return NO;
}
NSLog(#"no");
return YES;
}

Alright, I copy & tested your code, it works well, maybe somewhere else did wrong...
Create a new "Empty Template" Xcode project with ARC enabled, paste below into AppDelegat.m:
//
// AppDelegate.m
// WebTest
//
// Created by Elf Sundae on 8/5/13.
// Copyright (c) 2013 www.0x123.com. All rights reserved.
//
#import "AppDelegate.h"
#interface SampleViewController : UITableViewController
#end
#implementation SampleViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Sample Controller";
}
#end
#pragma mark -
#interface WebViewController : UIViewController <UIWebViewDelegate>
#end
#implementation WebViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIWebView *web = [[UIWebView alloc] initWithFrame:self.view.bounds];
web.delegate = self;
[self.view addSubview:web];
[web loadHTMLString:#"<a href='didTap://button1'><img src='cercle24px.png' /></a>" baseURL:nil];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:nil message:#"alert message" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
NSString *urlString = request.URL.absoluteString;
if ([urlString caseInsensitiveCompare:#"didtap://button1"] == NSOrderedSame) {
#define __use_method 3 // it could be: 1/2/3
#if (__use_method == 1)
SampleViewController *controller = [[SampleViewController alloc] init];
[self.navigationController pushViewController:controller animated:YES];
#elif (__use_method == 2)
/* method 2 */
SampleViewController *controller = [[SampleViewController alloc] init];
[self.navigationController performSelector:#selector(pushViewController:animated:)
withObject:controller
withObject:#(YES)];
#elif (__use_method == 3)
/* method 3 */
__unsafe_unretained __typeof(self) _self = self;
double delayInSeconds = 0.01;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
SampleViewController *controller = [[SampleViewController alloc] init];
[_self.navigationController pushViewController:controller animated:YES];
});
#endif
return NO;
}
return YES;
}
#end
#pragma mark -
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window makeKeyAndVisible];
self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:
[WebViewController new]];
return YES;
}
#end

Related

'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle in Xcode

I'm writing an iOS app that implements Google Cloud Messaging.
I want to receive the authorization token and print it on screen.
I installed everything necessary and I wrote the code following a tutorial on YouTube.
That's my code:
AppDelegate.h
#import <UIKit/UIKit.h>
#class ViewController;
#interface AppDelegate : UIResponder <UIApplicationDelegate>;
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) ViewController *viewController;
#property (nonatomic) NSString *getton;
#end
AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
#import "GoogleCloudMessaging.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize viewController = _viewController;
#synthesize getton;
- (void) dealloc {
[_window release];
[_viewController release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]] autorelease];
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
self.viewController = [[[ViewController alloc] initWithNibName:#"LaunchScreen.storyboard" bundle:nil] autorelease];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[self registerDeviceToken: deviceToken];
}
- (void) registerDeviceToken:(NSData *)deviceToken {
NSLog(#"Device Token: %#", deviceToken);
NSMutableString *string=[[NSMutableString alloc] init];
int length=[deviceToken length];
char const *bytes=[deviceToken bytes];
for (int i=0; i<length; i++) {
[string appendString:[NSString stringWithFormat:#"%02.2hhx",bytes[i]]];
}
NSLog(#"%#",string);
[self performSelectorInBackground:#selector(connectionWebRegister:)withObject:string];
[string release];
}
-(void) connectionWebRegister:(NSString *) deviceTokenString {
NSAutoreleasePool *pool = [NSAutoreleasePool new];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://serviceProvider/registerTokenId?tokenId=%#&app=",deviceTokenString]];
NSLog(#"APNS URL : %#",url);
NSData * res = [NSData dataWithContentsOfURL:url];
getton=deviceTokenString;
if (res!=nil) {
NSString *response = [[NSString alloc] initWithBytes: [res bytes] lenght:[res length] encoding: NSUTF8StringEncoding];
NSLog(#"%#", response);
[response release];
}
[pool drain];
}
- (void)application:(UIApplication *)app didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSLog(#"test");
NSMutableDictionary * test = [userInfo objectForKey:#"aps"];
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"MESSAGE"
message:[test objectForKey:#"alert"]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
#end
ViewController.h and ViewController.m are both empty.
But when simulator starts, it crashes with this error:
<'NSInternalInconsistencyException', reason: 'Could not load NIB in
bundle: 'NSBundle' > with an < Thread 1: signal SIGABRT > error in
Main.m .
I have searched a lot on internet to solve that problem, but I could not solve it.
So, are there somebody, who can help me? Thanks!
If you storyboard with mentioned name in question exists then
You should use,
UIStoryboard *storyboardobj=[UIStoryboard storyboardWithName:#"LaunchScreen" bundle:nil];
self.viewController = [storyboardobj instantiateInitialViewController];
instead of
self.viewController = [[[ViewController alloc] initWithNibName:#"LaunchScreen.storyboard" bundle:nil] autorelease];

Data (char*) appears corrupt when logged after pressing button

I'm quite newbie to iphone programming.
The problem is when I push a button, a data will be destroyed.
I can't find where my code is wrong and why. Please help me.
This is overview of my program.
1. load text data from "sample.txt"
2. log the data
3. When I push a button, it logs the data again.
AppDelegate.h
#import <UIKit/UIKit.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) UIButton *myButton1;
#property (assign) unsigned char* bytePtr;
#end
AppDelegate.m:
~snip~
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
self.myButton1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.myButton1 setFrame:CGRectMake(0, 0, 100 ,100)];
[self.myButton1 addTarget:self action:#selector(button1DidPushed) forControlEvents:UIControlEventTouchUpInside];
[self.myButton1 setTitle:#"push" forState:UIControlStateNormal];
[self.window addSubview:self.myButton1];
[self load];
return YES;
}
- (void) load
{
NSString* path = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"txt"];
NSData* data = [NSData dataWithContentsOfFile:path];
self.bytePtr = (unsigned char *)[data bytes];
NSLog(#"%s", self.bytePtr);
}
- (void)button1DidPushed
{
UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:#"Enter something..." message:#"" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
alerView.alertViewStyle = UIAlertViewStylePlainTextInput;
[alerView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"OK"])
{
}
NSLog(#"%s", self.bytePtr);
}
~snip~
sample.txt:
abcdefghijklmnopqrstuvwxyz
output:
abcdefghijklmnopqrstuvwxyz
<----- When I push the button the mark similar to "?" will appear on output window.(I couldn't show it here(It's probabily ascii code 2(STX))) That is why I think the data is destroyed.
Environment:
xcode 6.0.1
Thanks.
The issue is that you are not retaining the NSData object:
- (void) load
{
NSString* path = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"txt"];
NSData* data = [NSData dataWithContentsOfFile:path]; // here
self.bytePtr = (unsigned char *)[data bytes];
NSLog(#"%s", self.bytePtr);
}
Once that method returns the NSData object will be destroyed and therefore the buffer pointed to by self.bytePtr is no longer valid.
To solve this issue change self.bytePtr to an NSData object and store that instead.
First of all, in order to receive your alertView:clickedButtonAtIndex: method call, you need to set your UIAlertView delegate to self.
[alertView setDelegate:self] // make sure you set UIAlertViewDelegate protocol on the method owner
Otherwise you should use an NSString object initialized using initWithData:encoding:.

Send Audio by Email

How could I get the audio from phone and get it to share via email?
Will it available?
Can we share it simply like music at application?
Your question could have been better, you should show what you've tried, your specific problem, your actual results and your expected result.
Having said that, this sounded like a nice challenge.. so the answer follows.
I'm not sure if you wanted to get the music from the iPod or the app bundle so I implemented the iPod version as (in my opinion), it's more complex.
SSCCE:
main.m
#import "AppDelegate.h"
int main(int argc, char * argv[])
{
#autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
AppDelegate.h
#import UIKit;
#import MessageUI;
#import MediaPlayer;
#interface AppDelegate : UIResponder <UIApplicationDelegate, MFMailComposeViewControllerDelegate, MPMediaPickerControllerDelegate>
#property (strong, nonatomic) UIWindow *window;
#end
AppDelegate.m
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window makeKeyAndVisible];
UIViewController *controller = [[UIViewController alloc] init];
_window.rootViewController = controller;
MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeAny];
mediaPicker.delegate = self;
mediaPicker.allowsPickingMultipleItems = YES;
mediaPicker.prompt = #"Select songs to play";
[_window.rootViewController presentViewController:mediaPicker animated:YES completion:^{
}];
return YES;
}
-(void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
NSLog(#"Result:%d", result);
[controller dismissViewControllerAnimated:YES completion:nil];
}
-(void) mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
[mediaPicker dismissViewControllerAnimated:YES completion:^{
NSArray *recipents = #[#"a#b.com"];
MFMailComposeViewController *messageController = [[MFMailComposeViewController alloc] init];
messageController.mailComposeDelegate = self;
[messageController setToRecipients:recipents];
[messageController setMessageBody:#"Here is a music track" isHTML:NO];
[messageController setSubject:#"Music"];
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
for (MPMediaItem *item in mediaItemCollection.items)
{
NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];
AVAsset *asset = [AVAsset assetWithURL:url];
NSArray *presets = [AVAssetExportSession exportPresetsCompatibleWithAsset:asset];
AVAssetExportSession *session = [AVAssetExportSession exportSessionWithAsset:asset presetName:presets[0]];
session.outputURL = [[tmpDirURL URLByAppendingPathComponent:#"item"] URLByAppendingPathExtension:#"m4a"];
session.outputFileType = [session supportedFileTypes][0];
[session exportAsynchronouslyWithCompletionHandler:^{
NSData *data = [NSData dataWithContentsOfURL:session.outputURL];
[messageController addAttachmentData:data mimeType:#"audio/mp4" fileName:#"musicAttachment.m4a"];
}];
}
[_window.rootViewController presentViewController:messageController animated:YES completion:^{
}];
}];
}
-(void) mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker
{
}
#end

add an activity sheet/UI Alert dialog before initiating an operation in UIView

In an app i am developping I have a view which first appears whenever the user imports a doc to the app. What I want is to have a dialog box appear(could be an UIAlert or Activity sheet menu) asking the user if he really wants to import that file( Yes or cancel). I would like to know how to make the UIAlert/Actionsheet menu appear before the import action is performed, and how to assign an action to be done when user clicks on either Yes or No, or "Change file
The view that appears is called ProgressBarView.m/h. In it is the viewdidload like this:
- (void)viewDidLoad
{
[super viewDidLoad];
self.progressBar.progressTintColor = [UIColor colorWithRed:153.0/255 green:0 blue:0 alpha:1.0];
self.progressBar.progress = 0.0;
/*progressValueLabel = [NSString stringWithFormat:#"%.0f%%", (self.progressBar.progress * 100)];*/
self.progressTimer = [NSTimer scheduledTimerWithTimeInterval:0.3f
target:self
selector:#selector(changeProgressValue)
userInfo:nil
repeats:YES];
}
This is then called in the app delegate when the import starts in the appdidFinishLaunchwith options:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURL *url = (NSURL *)[launchOptions valueForKey:UIApplicationLaunchOptionsURLKey];
if (url != nil && [url isFileURL]) {
**[self handleImportURL:url];** // this is the function that handles the import
}
The function that does the import and calls the progressView is as follows:
- (void)handleImportURL:(NSURL *)url
{
// Show progress window
UIStoryboard * storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
__block PVProgressViewController * progressController = [storyboard instantiateViewControllerWithIdentifier:#"kProgressViewController"];
self.window.rootViewController = progressController;
// Perform import operation
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSError *outError;
NSString * csvString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&outError];
NSArray * array = [csvString csvRows];
[[PVDatabaseController sharedController] importArray:array progressHandler:^(float progress) {
progressController.progressBar.progress = progress;
}];
dispatch_async(dispatch_get_main_queue(), ^{
self.window.rootViewController = controller;
});
});
}
You could define your NSURL as an ivar, and call your handleImportURL: method in the appropriate clickedButtonAtIndex: method like this:
#implementation AppDelegate{
NSURL *_importURL;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
_importURL = (NSURL *)[launchOptions valueForKey:UIApplicationLaunchOptionsURLKey];
if (url != nil && [url isFileURL]) {
[self confirmImportAlert];
}
}
UIActionSheet:
- (void)confirmImportAlert {
UIActionSheet *myActionSheet = [[UIActionSheet alloc] initWithTitle:#"Your Title" delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:#"Yes", nil];
myActionSheet.delegate = self;
[myActionSheet showInView:self.window];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex == 0){
//initiate import
[self handleImportURL:_importURL];
}
else{
//don't initiate import
}
}
UIAlertView:
- (void)confirmImportAlert {
UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:#"Your Title" message:#"Your Message" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Yes", nil];
[myAlertView show];
}
- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex == 0){
//initiate import
[self handleImportURL:_importURL];
}
else{
//don't initiate import
}
}

Open Specific View when Opening App from Notification

I have just added push notifications to my app. I'm wanting to have so that when a user opens the app from a notification, it will open a specific view controller and not my rootViewController. Here is my AppDelegate:
#import "KFBAppDelegate.h"
#import "KFBViewController.h"
#import "AboutUs.h"
#import "ContactUs.h"
#import "KYFB.h"
#import "KFBNavControllerViewController.h"
#import "KFBTabBarViewController.h"
#import "RSFM.h"
#import "LegislatorInfo.h"
#import "Events.h"
#import "ActionAlertsViewController.h"
#import "UAirship.h"
#import "UAPush.h"
#import "UAAnalytics.h"
#implementation KFBAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// This prevents the UA Library from registering with UIApplcation by default when
// registerForRemoteNotifications is called. This will allow you to prompt your
// users at a later time. This gives your app the opportunity to explain the benefits
// of push or allows users to turn it on explicitly in a settings screen.
// If you just want everyone to immediately be prompted for push, you can
// leave this line out.
// [UAPush setDefaultPushEnabledValue:NO];
//Create Airship options dictionary and add the required UIApplication launchOptions
NSMutableDictionary *takeOffOptions = [NSMutableDictionary dictionary];
[takeOffOptions setValue:launchOptions forKey:UAirshipTakeOffOptionsLaunchOptionsKey];
// Call takeOff (which creates the UAirship singleton), passing in the launch options so the
// library can properly record when the app is launched from a push notification. This call is
// required.
//
// Populate AirshipConfig.plist with your app's info from https://go.urbanairship.com
[UAirship takeOff:takeOffOptions];
// Set the icon badge to zero on startup (optional)
[[UAPush shared] resetBadge];
// Register for remote notfications with the UA Library. This call is required.
[[UAPush shared] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert)];
// Handle any incoming incoming push notifications.
// This will invoke `handleBackgroundNotification` on your UAPushNotificationDelegate.
[[UAPush shared] handleNotification:[launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey]
applicationState:application.applicationState];
// self.tabBarController = [[UITabBarController alloc] initWithNibName:#"KFBViewController" bundle:nil];
KFBViewController *rootView = [[KFBViewController alloc] initWithNibName:#"KFBViewController" bundle:nil];
KFBNavControllerViewController *navController = [[KFBNavControllerViewController alloc] initWithRootViewController:rootView];
navController.delegate = rootView;
UIViewController *aboutUs = [[AboutUs alloc] initWithNibName:#"AboutUs" bundle:nil];
KFBNavControllerViewController *navController1 = [[KFBNavControllerViewController alloc] initWithRootViewController:aboutUs];
UIViewController *contactUs = [[ContactUs alloc] initWithNibName:#"ContactUs" bundle:nil];
KFBNavControllerViewController *navController2 = [[KFBNavControllerViewController alloc] initWithRootViewController:contactUs];
UIViewController *kyfb = [[KYFB alloc] initWithNibName:#"KYFB" bundle:nil];
KFBNavControllerViewController *navController3 = [[KFBNavControllerViewController alloc] initWithRootViewController:kyfb];
// UIViewController *rsfm = [[RSFM alloc] initWithNibName:#"RSFM" bundle:nil];
// KFBNavControllerViewController *navController4 = [[KFBNavControllerViewController alloc] initWithRootViewController:rsfm];
// UIViewController *li = [[LegislatorInfo alloc] initWithNibName:#"LegislatorInfo" bundle:nil];
// KFBNavControllerViewController *navController5 = [[KFBNavControllerViewController alloc] initWithRootViewController:li];
// UIViewController *events = [[Events alloc] initWithNibName:#"Events" bundle:nil];
// KFBNavControllerViewController *navController6 = [[KFBNavControllerViewController alloc] initWithRootViewController:events];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//self.viewController = [[KFBViewController alloc] initWithNibName:#"KFBViewController" bundle:nil];
//self.window.rootViewController = self.viewController;
self.tabBarController = [[KFBTabBarViewController alloc] init];
self.tabBarController.viewControllers = #[navController, navController1, navController2, navController3];
// self.tabBarController.customizableViewControllers = nil;
self.window.rootViewController = self.tabBarController;
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
UA_LDEBUG(#"Application did become active.");
// Set the icon badge to zero on resume (optional)
[[UAPush shared] resetBadge];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
[UAirship land];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// Updates the device token and registers the token with UA.
[[UAPush shared] registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *) error
{
UA_LERR(#"Failed To Register For Remote Notifications With Error: %#", error);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
UA_LINFO(#"Received remote notification: %#", userInfo);
// Send the alert to UA so that it can be handled and tracked as a direct response. This call
// is required.
[[UAPush shared] handleNotification:userInfo applicationState:application.applicationState];
// Optionally provide a delegate that will be used to handle notifications received while the app is running
// [UAPush shared].delegate = your custom push delegate class conforming to the UAPushNotificationDelegate protocol
// Reset the badge after a push received (optional)
[[UAPush shared] resetBadge];
}
-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
return UIInterfaceOrientationMaskAllButUpsideDown;
}
#end
And here is the view controller I want to open when opening a notification:
#import "ActionAlertsViewController.h"
#import "RSSChannel.h"
#import "RSSItem.h"
#import "WebViewController.h"
#import "CustomCellBackground.h"
#implementation ActionAlertsViewController
{
UIActivityIndicatorView *loadingIndicator;
}
#synthesize webViewController;
- (void)viewDidLoad
{
self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
self.title = #"Action Alerts";
loadingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
loadingIndicator.center = CGPointMake(160, 160);
loadingIndicator.hidesWhenStopped = YES;
[self.view addSubview:loadingIndicator];
[loadingIndicator startAnimating];
// UIRefreshControl *refresh = [[UIRefreshControl alloc] init];
// refresh.attributedTitle = [[NSAttributedString alloc] initWithString:#"Pull to Refresh"];
// [refresh addTarget:self action:#selector(refreshView:)forControlEvents:UIControlEventValueChanged];
// self.refreshControl = refresh;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(#"%# found a %# element", self, elementName);
if ([elementName isEqual:#"channel"])
{
// If the parser saw a channel, create new instance, store in our ivar
channel = [[RSSChannel alloc]init];
// Give the channel object a pointer back to ourselves for later
[channel setParentParserDelegate:self];
// Set the parser's delegate to the channel object
[parser setDelegate:channel];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// return 0;
NSLog(#"channel items %d", [[channel items]count]);
return [[channel items]count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// return nil;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"UITableViewCell"];
cell.textLabel.font=[UIFont systemFontOfSize:16.0];
}
RSSItem *item = [[channel items]objectAtIndex:[indexPath row]];
[[cell textLabel]setText:[item title]];
cell.backgroundView = [[CustomCellBackground alloc] init];
cell.selectedBackgroundView = [[CustomCellBackground alloc] init];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.highlightedTextColor = [UIColor darkGrayColor];
return cell;
}
- (void)fetchEntries
{
// Create a new data container for the stuff that comes back from the service
xmlData = [[NSMutableData alloc]init];
// Construct a URL that will ask the service for what you want -
// note we can concatenate literal strings together on multiple lines in this way - this results in a single NSString instance
NSURL *url = [NSURL URLWithString:#"http://kyfbnewsroom.com/category/public-affairs/notifications/feed/"];
// Put that URL into an NSURLRequest
NSURLRequest *req = [NSURLRequest requestWithURL:url];
// Create a connection that will exchange this request for data from the URL
connection = [[NSURLConnection alloc]initWithRequest:req delegate:self startImmediately:YES];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self)
{
[self fetchEntries];
}
return self;
}
// This method will be called several times as the data arrives
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
// Add the incoming chunk of data to the container we are keeping
// The data always comes in the correct order
[xmlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
/* We are just checking to make sure we are getting the XML
NSString *xmlCheck = [[NSString alloc]initWithData:xmlData encoding:NSUTF8StringEncoding];
NSLog(#"xmlCheck = %#", xmlCheck);*/
[loadingIndicator stopAnimating];
// Create the parser object with the data received from the web service
NSXMLParser *parser = [[NSXMLParser alloc]initWithData:xmlData];
// Give it a delegate - ignore the warning here for now
[parser setDelegate:self];
//Tell it to start parsing - the document will be parsed and the delegate of NSXMLParser will get all of its delegate messages sent to it before this line finishes execution - it is blocking
[parser parse];
// Get rid of the XML data as we no longer need it
xmlData = nil;
// Reload the table.. for now, the table will be empty
NSMutableArray *notActionAlerts = [NSMutableArray array];
for (RSSItem *object in channel.items) {
if (!object.isActionAlert) {
[notActionAlerts addObject:object];
}
}
for (RSSItem *object in notActionAlerts) {
[channel.items removeObject:object];
}
[[self tableView]reloadData];
NSLog(#"%#\n %#\n %#\n", channel, [channel title], [channel infoString]);
}
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
// Release the connection object, we're done with it
connection = nil;
// Release the xmlData object, we're done with it
xmlData = nil;
// Grab the description of the error object passed to us
NSString *errorString = [NSString stringWithFormat:#"Fetch failed: %#", [error localizedDescription]];
// Create and show an alert view with this error displayed
UIAlertView *av = [[UIAlertView alloc]initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Push the web view controller onto the navigation stack - this implicitly creates the web view controller's view the first time through
// [[self navigationController]pushViewController:webViewController animated:YES];
[self.navigationController pushViewController:webViewController animated:NO];
// Grab the selected item
RSSItem *entry = [[channel items]objectAtIndex:[indexPath row]];
// Construct a URL with the link string of the item
NSURL *url = [NSURL URLWithString:[entry link]];
// Construct a request object with that URL
NSURLRequest *req = [NSURLRequest requestWithURL:url];
// Load the request into the web view
[[webViewController webView]loadRequest:req];
webViewController.hackyURL = url;
// Set the title of the web view controller's navigation item
// [[webViewController navigationItem]setTitle:[entry title]];
}
/*
-(void)refreshView:(UIRefreshControl *)refresh
{
refresh.attributedTitle = [[NSAttributedString alloc] initWithString:#"Refreshing data..."];
// custom refresh logic would be placed here...
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM d, h:mm a"];
NSString *lastUpdated = [NSString stringWithFormat:#"Last updated on %#",[formatter stringFromDate:[NSDate date]]];
refresh.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated];
[refresh endRefreshing];
}
*/
#end
Here is the chunk of code I've added to my didFinishLaunchingWithOptions method. I've gotten almost everything working. The web views work now when selecting a row and the navigation bar is there and seemingly works as it should. The only trouble I'm having now is getting the tab bar to show up. Here is the chunk of code I'm currently using.
UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (notification)
{
ActionAlertsViewController *actionAlerts = [[ActionAlertsViewController alloc] initWithStyle:UITableViewStylePlain];
WebViewController *wvc = [[WebViewController alloc]init];
[actionAlerts setWebViewController:wvc];
KFBNavControllerViewController *navController7 = [[KFBNavControllerViewController alloc] initWithRootViewController:actionAlerts];
[self.window.rootViewController presentViewController:navController7 animated:NO completion:nil];
}
You could post a notification yourself when you receive a remote notification and by registering the viewcontroller to this notification, you could open a particular viewController once notification is received.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
[[NSNotificationCenter defaultCenter] postNotificationName:#"pushNotification" object:nil userInfo:userInfo];
}
In your FirstViewController.m register for listening to this notification.
-(void)viewDidLoad{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(pushNotificationReceived) name:#"pushNotification" object:nil];
}
Inside the method you could open particular viewController
-(void)pushNotificationReceived{
[self presentViewController:self.secondViewController animated:YES completion:nil];
}
Finally un-register current viewController from notification in dealloc method
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
If the app is opened from a notification, either of the two methods from your app delegate will be called
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
OR
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
In case of the latter, the launchOptions will let you know if the app was launched due to a remote notification or some other reason (see Launch Option Keys here)
Put in a check in these methods so that the specific viewcontroller will be opened if the app is launched from a notification.
You can do some thing like this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
// If application is launched due to notification,present another view controller.
UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (notification)
{
NotificationViewController *viewController = [[NotificationViewController alloc]initWithNibName:NSStringFromClass([NotificationViewController class]) bundle:nil];
[self.window.rootViewController presentModalViewController:viewController animated:NO];
[viewController release];
}
return YES;
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NotificationViewController *viewController = [[NotificationViewController alloc]initWithNibName:NSStringFromClass([NotificationViewController class]) bundle:nil];
[self.window.rootViewController presentModalViewController:viewController animated:NO];
[viewController release];
}

Resources