iOS Events & Notifications
1.
UIApplicationDelegate
2.
UIApplication Events
3.
Image Capturing
4.
UIWebView
5.
NSUserDefaults & Setting Bundle
6.
Local Notification
7.
Introduction to APN
UIApplicationDelegate:
application:didFinishLaunchingWithOptions:
application
The delegating application object.
launchOptions
A dictionary indicating the reason the application was
launched (if any). The contents of this dictionary may be empty in situations
where the user launched the application directly. See “Launch Options Keys” in UIApplication
Class Reference for descriptions of these
keys.
application:didReceiveLocalNotification:
Sent
to the delegate when a running application receives a local notification.
application
The application that received the local notification.
notification
A local notification that encapsulates details about
the notification, potentially including custom data.
applicationDidBecomeActive:
Tells
the delegate that the application has become active.
This
method is called to let your application know that it moved from the inactive
to active state. This can occur because your application was launched by the
user or the system. Applications can also return to the active state if the
user chooses to ignore an interruption (such as an incoming phone call or SMS
message) that sent the application temporarily to the inactive state.
applicationDidEnterBackground:
Tells
the delegate that the application is now in the background.
applicationDidReceiveMemoryWarning:
Tells
the delegate when the application receives a memory warning from the system.
applicationWillEnterForeground:
Tells
the delegate that the application is about to enter the foreground.
applicationWillResignActive:
Tells
the delegate that the application is about to become inactive.
applicationWillTerminate:
Tells
the delegate when the application is about to terminate.
UIApplication Events:
-sendEvent:
Subclasses may override this method to intercept
incoming events for inspection and special dispatching. iOS calls this method
for public events only.
-sendAction:to:from:forEvent:
Normally, this method is invoked by a UIControl object that the user has
touched. The default implementation dispatches the action method to the given
target object or, if no target is specified, to the first responder. Subclasses
may override this method to perform special dispatching of action messages.
-beginIgnoringInteractionEvents:
Tells the receiver to suspend the handling of
touch-related events.You typically call this method before starting an
animation or transition. Calls are nested with the endIgnoringInteractionEvents method.
-endIgnoringInteractionEvents:
Tells the receiver to resume the handling of
touch-related events.You typically call this method when, after calling the beginIgnoringInteractionEvents method, the animation or
transition concludes. Nested calls of this method should match nested calls of
the beginIgnoringInteractionEvents method.
-isIgnoringInteractionEvents:
Returns whether the
receiver is ignoring events initiated by touches on the screen.
Image Capture
The
UIImagePickerController class manages customizable, system-supplied user
interfaces for taking pictures and movies on supported devices, and for
choosing saved images and movies for use in your app. An image picker
controller manages user interactions and delivers the results of those
interactions to a delegate object.
The
role and appearance of an image picker controller depend on the source type you
assign to it before you present it.
· A sourceType of UIImagePickerControllerSourceTypeCamera provides a user interface for taking a new picture or
movie (on devices that support media capture).
· A sourceType
of UIImagePickerControllerSourceTypePhotoLibrary or UIImagePickerControllerSourceTypeSavedPhotosAlbum provides a user interface for choosing among saved
pictures and movies.
To
use an image picker controller containing its default controls, perform these
steps:
1.
Verify that the
device is capable of picking content from the desired source. Do this calling
the isSourceTypeAvailable: class method, providing a constant from the “UIImagePickerControllerSourceType” enum.
2.
Check which media
types are available, for the source type you’re using, by calling the availableMediaTypesForSourceType: class method. This lets you distinguish between a
camera that can be used for video recording and one that can be used only for
still images.
3.
Tell the image
picker controller to adjust the UI according to the media types you want to
make available—still images, movies, or both—by setting the mediaTypes property.
4.
Present the user
interface by calling the presentViewController:animated:completion: method of the currently active view controller,
passing your configured image picker controller as the new view controller.
On iPad, present the user interface using a popover.
Doing so is valid only if the sourceType property of the image picker controller is set to UIImagePickerControllerSourceTypeCamera.
5.
When the user taps
a button to pick a newly captured or saved image or movie, or cancels the
operation, dismiss the image picker using your delegate object. For newly
captured media, your delegate can then save it to the Camera Roll on the
device. For previously saved media, your delegate can then use the image data
according to the purpose of your app.
Mail Component:
canSendMail
Returns
a Boolean indicating whether the current device is able to send email.
setSubject:
Sets
the initial text for the subject line of the email.
setToRecipients:
Sets
the initial recipients to include in the email’s “To” field.
MFMailComposeViewControllerDelegate:
mailComposeController:didFinishWithResult:error:
Tells
the delegate that the user wants to dismiss the mail composition view.
controller
The view controller object managing the mail
composition view.
result
The result of the user’s action.
error
If an error occurred, this parameter contains an error
object with information about the type of failure.
e.g.
picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setTitle:@"Email"];
[picker setSubject:emailSubject];
[picker setMessageBody:emailBody isHTML:NO];
picker.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
picker.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentModalViewController:picker animated:YES];
NSUserDefaults & Setting Bundle:
Saving:
NSUserDefaults *prefs = [NSUserDefaults
standardUserDefaults];
// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];
// saving an NSInteger
[prefs setInteger:42 forKey:@"integerKey"];
[prefs setInteger:42 forKey:@"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:@"doubleKey"];
[prefs setDouble:3.1415 forKey:@"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:@"floatKey"];
[prefs setFloat:1.2345678 forKey:@"floatKey"];
// This is suggested to synch
prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];
[prefs synchronize];
Retrieving
NSUserDefaults *prefs =
[NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];
NSString *myString = [prefs stringForKey:@"keyToLookupString"];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:@"integerKey"];
NSInteger myInt = [prefs integerForKey:@"integerKey"];
// getting an Float
float myFloat = [prefs floatForKey:@"floatKey"];
float myFloat = [prefs floatForKey:@"floatKey"];
Control type
Description
Text field
The text field type
displays a title (optional) and an editable text field. You can use this type
for preferences that require the user to specify a custom string value.
The key for this type is PSTextFieldSpecifier.
Title
The title type displays a
read-only string value. You can use this type to display read-only preference
values. (If the preference contains cryptic or nonintuitive values, this type
lets you map the possible values to custom strings.)
The key for this type is PSTitleValueSpecifier.
Toggle switch
The toggle switch type
displays an ON/OFF toggle button. You can use this type to configure a
preference that can have only one of two values. Although you typically use
this type to represent preferences containing Boolean values, you can also use
it with preferences containing non-Boolean values.
The key for this type is PSToggleSwitchSpecifier.
Slider
The slider type displays a
slider control. You can use this type for a preference that represents a range
of values. The value for this type is a real number whose minimum and maximum
value you specify.
The key for this type is PSSliderSpecifier.
Multivalue
The multivalue type lets
the user select one value from a list of values. You can use this type for a
preference that supports a set of mutually exclusive values. The values can be
of any type.
The key for this type is PSMultiValueSpecifier.
Group
The group type is for
organizing groups of preferences on a single page. The group type does not
represent a configurable preference. It simply contains a title string that is
displayed immediately before one or more configurable preferences.
The key for this type is PSGroupSpecifier.
Child pane
The child pane type lets
the user navigate to a new page of preferences. You use this type to implement
hierarchical preferences. For more information on how you configure and use
this preference type, see “Hierarchical
Preferences.”
The key for this type is PSChildPaneSpecifier.
Configuring a Settings Page: A Tutorial
This section shows you how
to configure a Settings page to display the controls you want.
1.
Disclose the
Preference Items key to display the default items that come with the template.
2.
Change the title
of Item 0 to Sound.
·
Disclose Item 0 of Preference Items.
·
Change the value
of the Title key from Group to Sound.
·
Leave the Type key set to Group.
·
Click the
disclosure triangle of the item to hide its contents.
3.
Create the first
toggle switch for the renamed Sound group.
·
Select Item 2 (the toggle switch item) of Preference Items and choose Edit > Cut.
·
Select Item 0 and choose Edit > Paste. (This moves the toggle
switch item in front of the text field item.)
·
Disclose the
toggle switch item to reveal its configuration keys.
·
Change the value
of the Title key to Play Sounds.
·
Change the value
of the Identifier key to play_sounds_preference.
·
Click the
disclosure triangle of the item to hide its contents.
4.
Create a second
toggle switch for the Sound group.
·
Select Item 1 (the Play Sounds toggle switch).
·
Choose Edit >
Copy.
·
Choose Edit
>Paste to place a copy of the toggle switch right after the first one.
·
Disclose the new
toggle switch item to reveal its configuration keys.
·
Change the value
of its Title key to 3D Sound.
·
Change the value
of its Identifier key to 3D_sound_preference.
·
Click the
disclosure triangle of the item to hide its contents.
At
this point, you have finished the first group of settings and are ready to
create the User Info group.
5.
Change Item 3 into a Group control and name it User Info.
·
Click Item 3 in the Preferences Items. This displays a pop-up menu with a list of item types.
·
From the pop-up
menu, choose Group to change the type of the control.
·
Disclose the
contents of Item 3.
·
Set the value of
the Title key to User Info.
·
Click the
disclosure triangle of the item to hide its contents.
6.
Create the Name
field.
·
Select Item 4 in the Preferences Items.
·
Using the pop-up
menu, change its type to Text Field.
·
Set the value of
the Title key to Name.
·
Set the value of
the Identifier key to user_name.
·
Click the
disclosure triangle of the item to hide its contents.
7.
Create the
Experience Level settings.
·
Select Item 4.
·
Control-click the
editor window and select Add Row to add a new item.
·
Set the type of
the new item to Multi
Value.
·
Disclose the
item’s contents and set its title to Experience Level, its identifier to experience_preference, and its default value to 0.
·
With the Default
Value key selected, Control-click and select Add Row to add a Titles array.
·
Select the Titles array and press Return to add a new subitem.
·
Add two more
subitems to create a total of three items.
·
Set the values of
the subitems to Beginner, Expert,
and Master.
·
Hide the key’s
subitems.
·
Add a new item
for the Values array.
·
Add three
subitems to the Values array and set their values to 0, 1, and 2.
·
Hide the contents
of Item 5.
8.
Add the final
group to your settings page.
·
Create a new item
and set its type to Group and its title to Gravity.
·
Create another
new item and set its type to Slider,
its identifier to gravity_preference, its default value to 1, and
its maximum value to 2.
UIWebView:
1. use the UIWebView class to embed web content in your
application. To do so, you simply create a UIWebView object, attach it to a
window, and send it a request to load web content. You can also use this class
to move back and forward in the history of webpages, and you can even set some
web content properties programmatically.
2. Use the loadRequest: method to begin loading web content, the stopLoading method to stop loading, and the loading property to find out if a web view is in the process of
loading.
3.Loading a document into a UIWebView.
|
-(void)loadDocument:(NSString*)documentName
inView:(UIWebView*)webView
{
NSString *path = [[NSBundle mainBundle] pathForResource:documentName
ofType:nil];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
}
// Calling -loadDocument:inView:
[self loadDocument:@"mydocument.rtfd.zip"
inView:self.myWebview];
|
loadHTMLString:baseURL:
Sets the main page content
and base URL.
- (void)loadHTMLString:(NSString *)string
baseURL:(NSURL *)baseURL
reload
Reloads the current page.
StopLoading
Stops the loading of any
web content managed by the receiver.
StringByEvaluatingJavaScriptFromString:
Returns the result of
running a script.
Scheduling Local Notifications
Creating and scheduling
local notifications in iOS requires that you perform a few simple steps:
1.
Allocate and
initialize a UILocalNotification object.
2.
Set the date and
time that the operating system should deliver the notification. This is the fireDate property.
If
you set the timeZone property to the NSTimeZone object for the current locale, the system
automatically adjusts the fire date when the device travels across (and is
reset for) different time zones. (Time zones affect the values of date
components—that is, day, month, hour, year, and minute—that the system
calculates for a given calendar and date value.) You can also schedule the
notification for delivery on a recurring basis (daily, weekly, monthly, and so
on).
3.
Configure the
substance of the notification: alert, icon badge number, and sound.
·
The alert has a
property for the message (the alertBody
property) and for the title of the action button or slider (alertAction); both of these string values can be
internationalized for the user’s current language preference.
·
You set the badge
number to display on the application icon through the applicationIconBadgeNumber property.
·
You can assign
the filename of a nonlocalized custom sound in the application’s main bundle to
the soundName property; to get the default system sound, assign UILocalNotificationDefaultSoundName. Sounds should always accompany an alert message or
icon badging; they should not be played otherwise.
4.
Optionally, you
can attach custom data to the notification through the userInfo property.
Keys
and values in the userInfo dictionary must be property-list objects.
5.
Schedule the
local notification for delivery.
You
schedule a local notification by calling the UIApplication method scheduleLocalNotification:. The application uses the fire date specified in the UILocalNotification object for the moment of delivery. Alternatively, you
can present the notification immediately by calling the presentLocalNotificationNow: method.
-
(void)scheduleNotificationWithItem:(ToDoItem *)item interval:(int)minutesBefore
{
NSCalendar *calendar = [NSCalendar
autoupdatingCurrentCalendar];
NSDateComponents *dateComps =
[[NSDateComponents alloc] init];
[dateComps setDay:item.day];
[dateComps setMonth:item.month];
[dateComps setYear:item.year];
[dateComps setHour:item.hour];
[dateComps setMinute:item.minute];
NSDate *itemDate = [calendar
dateFromComponents:dateComps];
[dateComps release];
UILocalNotification *localNotif =
[[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = [itemDate
addTimeInterval:-(minutesBefore*60)];
localNotif.timeZone = [NSTimeZone
defaultTimeZone];
localNotif.alertBody = [NSString
stringWithFormat:NSLocalizedString(@"%@ in %i minutes.", nil),
item.eventName,
minutesBefore];
localNotif.alertAction =
NSLocalizedString(@"View Details", nil);
localNotif.soundName =
UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
NSDictionary *infoDict = [NSDictionary
dictionaryWithObject:item.eventName forKey:ToDoItemKey];
localNotif.userInfo = infoDict;
[[UIApplication sharedApplication]
scheduleLocalNotification:localNotif];
[localNotif release];
}
APN:
A push notification
from a provider to a client application
Figure 3-1 is a greatly
simplified depiction of the virtual network APNs makes possible among providers
and devices. The device-facing and provider-facing sides of APNs both have
multiple points of connection; on the provider-facing side, these are called
gateways. There are typically multiple providers, each making one or more
persistent and secure connections with APNs through these gateways. And these
providers are sending notifications through APNs to many devices on which their
client applications are installed. Figure 3-2 is a slightly more realistic
depiction.
