1. Trang chủ
  2. » Công Nghệ Thông Tin

iPhone SDK 3 Programming Advanced Mobile Development for Apple iPhone and iPod touc phần 8 ppsx

68 214 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 68
Dung lượng 1,03 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

In addition, you need to add the following import statement to yourcode: #import 17.1.1 Determining network connectivity via EDGE or GPRS Listing 17.2 shows the cellularConnected method

Trang 1

Since the UI component instance is the delegate of the alert view, it defines thealertView:clickedButtonAtIndex: We simply cancel the thread by sending a cancelmessage to it.

self.progress = [[[ProgressAlertView alloc] init] autorelease];

Listing 16.10 The compute method used in demonstrating the usage of the ProgressAlertViewcomponent

Trang 2

First, we showed how to build an alert view with a text field in it, in Section 16.1 Next, Section 16.2presented a table view inside an alert view Finally, Section 16.3 showed how to build a progressalert view.

Problems

(1) Build a tabbed control UI component For each tab, the user should be able to provide justthe title and the view In addition, an optional title for the control should be accommodated.The UI component manages the switching from one view to the other The UI componentshould support a variable number of tabs and variable length of the titles The UI component

Trang 3

should support scrolling if a given view has a height that exceeds the available space for it.See Figure 16.6 for an example.

Figure 16.6 The tabbed control UI component

Trang 5

Advanced Networking

This chapter addresses several advanced networking topics We start by looking in Section 17.1 athow we can determine the network connectivity of the device This is important for several reasons.First, your application needs to determine the status of network connectivity and alert the user ofconnectivity problems instead of presenting an empty view to the user In addition, some applicationsrequire WiFi connection for specific services (e.g., downloading large files) You should be able toenable such services dynamically, based on the connectivity of the device

After that, we tackle the issue of uploading multimedia content (e.g., photos) to remote servers,

in Section 17.2 Next, In Section 17.3, we present a category on NSString that allows you toeasily compute the MD5 digest of a string This is important as some services, such as Flickr,require posting parameters with the appropriate signature Section 17.4 then shows you how topresent a responsive table view whose data rows are fed from the Internet without sacrificing theuser experience Next, Section 17.5 addresses the topic of push notification Section 17.6 discussessending email from within your iPhone application Finally, Section 17.7 summarizes the chapter

17.1 Determining Network Connectivity

In this section, we look at a mechanism that allows you to determine the network connectivity of thedevice We develop the following three methods in a category onUIDeviceclass:

• cellularConnected This method is used to determine whether the device is connected tothe network via EDGE or GPRS

• wiFiConnected This method is used to determine whether the device is connected to thenetwork on a WiFi

• networkConnected This method is used to determine network connectivity in general

Listing 17.1 shows the declaration of the category

Trang 6

Listing 17.1 A category on UIDevice for network connectivity.

@interface UIDevice (DeviceConnectivity)

+(BOOL)cellularConnected;

+(BOOL)wiFiConnected;

+(BOOL)networkConnected;

@end

In order to use the methods in this section, you need to add theSystemConfigurationframework

as explained in Section D.4 In addition, you need to add the following import statement to yourcode:

#import <SystemConfiguration/SCNetworkReachability.h>

17.1.1 Determining network connectivity via EDGE or GPRS

Listing 17.2 shows the cellularConnected method which determines whether the device isconnected via EDGE or GPRS

Listing 17.2 The cellularConnected method for determining connectivity to the network via EDGE orGPRS

Trang 7

You pass in the allocator in the first argument An allocator is used throughout Core Foundation forallocating and deallocating Core Foundation objects In our case, we just use the default allocator

by obtaining it using theCFAllocatorGetDefault() function The second parameter is the nodename (e.g.,google.com) that you want to test reachability to

After obtaining the reachability reference, the method determines network connectivity to the host bycalling theSCNetworkReachabilityGetFlags() function You pass in the network reference and

a reference to theflagslocal variable (32-bit number) The method checks theflagsby lookingfor a 1 in bit 18 If it is 1, that means the device is reachable via a cellular connection, such as EDGE

or GPRS

17.1.2 Determining network connectivity in general

Listing 17.3 shows a method that determines network connectivity in general

Listing 17.3 The method networkConnected that determines network connectivity

17.1.3 Determining network connectivity via WiFi

Finally, the following method determines WiFi connectivity by checking for network connectivityvia a transport other than EDGE/GPRS

+(BOOL)wiFiConnected{

if([self cellularConnected]){

Trang 8

return NO;

}

return [self networkConnected];

}

17.2 Uploading Multimedia Content

In this section, we will see how we can use theNSURLConnection class to upload multimediacontent to a remote server For demonstration purposes, we will use the example of uploading aphoto along with several other parameters to a remote server The procedure presented here alsoapplies to uploading other types of multimedia content (e.g., audio)

To communicate with a server, you follow these steps:

1 Create a request (instance ofNSURLRequestclass or its subclasses)

2 Configure that request with the url (an instance ofNSURLclass)

3 Specify theHTTPmethod (Post,Get, etc.)

4 Set the values of some of the request headers

5 Build the request body (instance ofNSDataclass) and assign it to the request

6 Use either a synchronous or asynchronous version of the NSURLConnection to send therequest to the server

7 Obtain the response from the server and act according to the HTTP status code and/orapplication-level return values

Listing 17.4 shows a method that posts a photo to a server

Listing 17.4 A method that posts a photo to a server

-(void)postPhoto:(UIImage *)_photo withLat:(float)_lat

NSString *contentType = [NSString stringWithFormat:

@"multipart/form-data; boundary=%@", boundary];

[req setValue:contentType forHTTPHeaderField:@"Content-type"];

NSMutableData *postBody = [NSMutableData data];

[postBody appendData:[[NSString stringWithFormat:

@" %@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];[self appendPhoto:_photo

withParamName:@"photo[uploaded_data]"

toData:postBody];

[self appendParamValue:_caption

withParamName:@"photo[caption]"

Trang 9

[self appendParamValue:[NSNumber numberWithFloat:_lat]

withParamName:@"photo[lat]" toData:postBody];

[self appendParamValue:[NSNumber numberWithFloat:_lng]

withParamName:@"photo[lng]" toData:postBody];

[postBody appendData:[[NSString stringWithFormat:

@"\r\n %@ \r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];[req setHTTPBody:postBody];

NSHTTPURLResponse * returnResponse = nil;

NSError * returnError = nil;

NSData *returnData =

[NSURLConnection sendSynchronousRequest:req

returningResponse:&returnResponseerror:&returnError];

int statusCode = returnResponse.statusCode;

NSString *str = [[[NSString alloc]

initWithData:returnDataencoding:NSUTF8StringEncoding] autorelease];

if([str isEqualToString:@"OK"] &&(statusCode == 200) && !returnError){NSLog(@"Photo uploaded successfully! Status code: 200");

Next, we set theHTTPmethod type toPostand theContent-typeto:

multipart/form-data; boundary= -75023658052007

The value for the boundary should be a unique pattern that does not occur within the post data.1After that, we add the parts of this post one after the other to a mutableNSDataobject The separatorsare needed between these parameters and should be used literally, otherwise the post will be invalid.Listing 17.5 shows the method used to add the caption, and the geo-data to a post body by thepostPhoto:withLat:withLng:andCaption:method

1 RFC1867 – Form-based File Upload in HTML, http://www.faqs.org/rfcs/rfc1867.html

Trang 10

Listing 17.5 A method that adds a parameter to a post data.

-(void)appendParamValue:(id)_value withParamName:(NSString*)_param

toData:(NSMutableData*)_data{

NSString *_tmp = [NSString stringWithFormat:

@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", _param];

[_data appendData:[[NSString stringWithFormat:

@"\r\n %@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];[_data appendData:[_tmp dataUsingEncoding:NSUTF8StringEncoding]];

[_data appendData:[[[_value description] urlEncodedVersion]

dataUsingEncoding:NSUTF8StringEncoding]];

}

Again, the separator is defined by the RFC and should be used as is TheNSNumberandNSStringclasses define thedescriptionmethod in a way suitable for our purpose If you would like to usethis method to add a parameter of different type, make sure that itsdescriptionmethod is defined

in the correct way

Listing 17.6 shows the method for adding a photo parameter to the post body

Listing 17.6 Appending a photo to a post body after compression

-(void)appendPhoto:(UIImage*)_photo withParamName:(NSString*)_param

toData:(NSMutableData*)_data{

NSData *_photoData = UIImageJPEGRepresentation(_photo, 0.6);

NSString *_tmp = [NSString stringWithFormat:

@"Content-Disposition: form-data; name=\"%@\"; filename=\"p.jpg\"\r\n",_param];

[_data appendData:[_tmp dataUsingEncoding:NSUTF8StringEncoding]];

[_data appendData:[@"Content-Type: image/jpeg\r\n\r\n"

One last comment about communicating with a server You need to encode the data Listing 17.7shows a category onNSStringto allow strings to produce encoded versions of their content ThemethodurlEncodedVersionsimply replaces all occurrences of an encodable character with theencoded version of that character

Listing 17.7 A category on NSString to extend strings with the ability to produce encoded versions ofthemselves

@interface NSString(URL_ENCODE)

-(NSString *)urlEncodedVersion;

Trang 11

NSMutableString *tempStr = [[self mutableCopy] autorelease];

for(int i = 0; i < [escapeChars count]; i++) {

[tempStr replaceOccurrencesOfString:[escapeChars objectAtIndex:i]

withString:[replaceChars objectAtIndex:i]

options:NSLiteralSearchrange:NSMakeRange(0,[tempStr length])];

}

return [[tempStr copy] autorelease];

}

@end

You can simply post a photo as follows:

[self postPhoto:[UIImage imageNamed:@"clouds.jpg"]

withLat:38.44 withLng:-97.76

andCaption:@"This is a nice photo!"];

Consult theupload_imageproject files for a complete iPhone client and Rails server source code.These projects are available from the source downloads

17.3 Computing MD5 Hash Value

MD5 is an algorithm which generates a 128-bit hash value for a given string MD5 is often used tocheck the integrity of files downloaded from the Internet MD5 is also used by some web servicessuch as Flickr This section presents a category onNSStringto allow a string to produce an MD5digest of its content

Listing 17.8 shows a category onNSStringdefining themd5 method which generates a 128-bitdigest on the value stored in the instance Themd5method uses theCC_MD5function to compute thedigest, and it then outputs the hexadecimal representation of the result

Trang 12

Listing 17.8 A category on NSString defining the md5 method which generates a 128-bit digest from thevalue stored in the instance.

const char *cStrValue = [self UTF8String];

unsigned char theResult[CC_MD5_DIGEST_LENGTH];

CC_MD5(cStrValue, strlen(cStrValue), theResult);

return [NSString stringWithFormat:

@"%02X%02X%02X%02X%02X%02X%02X%02X"

@"%02X%02X%02X%02X%02X%02X%02X%02X",

theResult[0], theResult[1], theResult[2],

theResult[3], theResult[4], theResult[5],

theResult[6], theResult[7], theResult[8],

theResult[9], theResult[10], theResult[11],

theResult[12], theResult[13], theResult[14],

theResult[15]

];

}

@end

The following code fragment shows a demonstration of the usage of this category:

NSString *value1 = @"The quick brown fox jumps over the lazy dog";NSString *value2 = @"The quick brown fox jumps over the lazy dog.";NSLog(@"MD5 of zero-length string is %@", [@"" md5]);

NSLog(@"MD5(%@) = %@", value1, [value1 md5]);

NSLog(@"MD5(%@) = %@", value2, [value2 md5]);

The output (after removing extra logging information) is as follows:

MD5 of zero-length string is D41D8CD98F00B204E9800998ECF8427EMD5(The quick brown fox jumps over the lazy dog) = \

Trang 13

17.4 Multithreaded Downloads

In this section, we develop an application that presents a table view with downloadable resources.The download of a resource will not start until the corresponding cell hosting that resource becomesvisible If the resource has been successfully downloaded, that resource is used to decorate the cell

If, on the other hand, that resource has not been downloaded yet, we ask the resource to downloaditself in the background If the resource cannot be download due to network or application failure,

we signal failure to the user by using a bundled image (a red X) instead

17.4.1 The application

In the following section, we develop the Multithreaded Download application The source code ofthe complete application can be found in the MThreadedDownloadsproject available from thesource downloads

Figure 17.1 shows a screenshot of the application

Figure 17.1 Screenshot of the Multithreaded Downloads application

At the heart of our application is the InternetResourceclass; a class that encapsulates thedownload of the resource in a new thread We start by developing this class and then write a tableview controller that uses it

Trang 14

The Internet Resource class

TheInternetResourceclass encapsulates an Internet resource that is downloaded, on demand, in

a separate thread (i.e., without locking the UI of the user) Listing 17.9 shows the interface for thisclass

Listing 17.9 The interface for the InternetResource class

#define FinishedLoading @"FinishedLoading"

@interface InternetResource : NSObject {

@property(nonatomic, retain) NSString *url;

@property(nonatomic, retain) NSString *title;

@property(nonatomic, retain) UIImage *image;

@property(nonatomic, assign) STATUS status;

@end

An object of this class is initialized with the title of the resource and its URL AnInternetResourceobject can be in one of the following four states:

• NEW It has just been created

• FETCHING It has received astartmessage and is currently fetching the resource from theInternet

• COMPLETE It has successfully downloaded the resource

• FAILED A network or application-level failure has occurred

To access the state of the resource, objects should use the statusproperty If the object is inCOMPLETEstate, the picture can be retrieved from theimageproperty

The following shows the implementation of the initializer

-(id)initWithTitle:(NSString*)_title andURL:(NSString*)_url{

Trang 15

if(self = [super init]){

runUntilDate:[NSDate dateWithTimeIntervalSinceNow:60]];

2 Remember, every thread needs its ownautoreleasepool.

Trang 16

toFAILED Since other objects might access this property, we synchronize to prevent corrupted data.It’s always a good idea to synchronize.

Trang 17

The Table View controller

Now that we have multithreaded downloads, we can build a simple table view controller, populate itwith Internet resources, and show it to the user

Listing 17.10 shows the initializer of the table view controller

Listing 17.10 The initializer of the table view controller used in the Multithread Downloads application

- (id)initWithStyle:(UITableViewStyle)style {

if (self = [super initWithStyle:style]) {

[[NSNotificationCenter defaultCenter]

addObserver:selfselector:@selector(handleFinishedLoading:)name:FinishedLoading object:nil];

self.iResources = [NSArray arrayWithObjects:

[[[InternetResource alloc] initWithTitle:@"First pic"

andURL:BAD_RESOURCE_URL2] autorelease],[[[InternetResource alloc] initWithTitle:@"Second pic"

andURL:SOME_RESOURCE_URL] autorelease],

Trang 18

[[[InternetResource alloc] initWithTitle:@"Third pic"

andURL:SOME_RESOURCE_URL] autorelease],[[[InternetResource alloc] initWithTitle:@"Fourth pic"

andURL:SOME_RESOURCE_URL] autorelease],[[[InternetResource alloc] initWithTitle:@"Fifth pic"

andURL:SOME_RESOURCE_URL] autorelease],[[[InternetResource alloc] initWithTitle:@"Sixth pic"

andURL:SOME_RESOURCE_URL] autorelease],nil];

}

return self;

}

We first add the controller as an observer for the notificationFinishedLoading After that, an array

ofInternetResourceobjects are created and put in a array

The table view controller adds a delegate and a data source to the table view Listing 17.11 showsthetableView:cellForRowAtIndexPath:for the table view controller The method obtains theInternetResourceobject corresponding to the cell After that, it displays the appropriate imagedepending on the state of the resource

Listing 17.11 The tableView:cellForRowAtIndexPath: for the table view controller ing multithreaded downloading

Trang 19

Finally, thedeallocmethod of the controller frees the resources and removes itself from being anobserver to any notification.

Trang 20

The message sent by the server to Apple to be delivered to a specific application is tagged with adevice token This device token is computed by the iPhone application and communicated to theserver This token is usually communicated to the server once and saved on the server thereafter.When a push notification message is received by the device, the operating system checks to see ifthe targeted application is running If that is the case, the application’s delegate of the application issent the message If the application is not running, an alert is shown to the user with the option tolaunch the target application.

Development of a push notification involves coding for the server and the client In addition, anSSL certificate must be generated for each application provisioned for push notification This SSLcertificate must be installed on the server The client does use SSL authentication, but you do nothave to manage that

17.5.1 Configuring push notification on the server

In this section, we outline the major steps needed to set up a server application that can send pushnotifications to our iPhone application Some of the steps here are needed for the client side as well

Configuring the App ID

Click on the iPhone Developer Program Portal in the iPhone Dev Center Select App IDs from themenu as shown in Figure 17.2

Click on the Add ID button as shown in Figure 17.3

An App ID is needed so that the notification server and the iPhone OS can know how to deliver themessage that your server sends to a given application An App ID consists of two parts:

• Bundle seed ID This is a 10-digit number that Apple automatically generates for you during

the App ID creation process

• Bundle identifier This part is determined by you the developer Usually, it is a string in

reverse-DNS format such ascom.mycompany.appname

Trang 21

Figure 17.2 Selecting the App IDs from the menu.

Figure 17.3 The Add ID button

Under the Manage tab, you will see two text boxes that you need to fill in In the first field, you enter

a distinguishable name for this App ID This is used for display purposes only and does not affectthe App ID

In the second text field, you enter the Bundle Identifier Figure 17.4 shows an example

Figure 17.4 Creating the App ID in the program portal

After filling in the two required fields, you hit Submit The App ID will be generated and you will

be returned to the page where all your App IDs are listed You should see your App ID as one of theitems listed as shown in Figure 17.5

Trang 22

Figure 17.5 The newly-created App ID.

Under the ID column, you will see the App ID which is composed of the 10-digit random numberand your bundle identifier You will also notice that under the Apple Push Notification column itsays that the service is Available and the icon is in orange color

Configuring the App ID for notification

We need to configure the App ID for notification Click on the Configure button The Configure App

ID page will appear You will need to enable Push by checking the Enable Push Notification Servicesshown in Figure 17.6

Figure 17.6 The Enable Push Notification Services check box

Once you have checked the box, the Configure button (see Figure 17.7) becomes enabled, so clickit

Figure 17.7 The Configure button

Once you have clicked the Configure button, a pop-up window appears with a new workflow Thiswizard will guide you through the process of generating an SSL certificate to be used by the server.Figure 17.8 shows that window

Trang 23

Figure 17.8 The first window in the wizard for generating the SSL certificate for push notification.

Generating the SSL certificate

The first step in this process is the generation of the certificate signing request (CSR) using theKeychain Access application Launch the Keychain Access application and select from the menuKeychain Access > Certificate Assistant > Request a Certificate from a Certificate Authority Fill inthe request similar to the one shown in Figure 17.9 and hit Continue

Once you clicked on Continue, a dialog box appears asking you for the location of the CSR file.Choose a location such as the Desktop and hit Save as shown in Figure 17.10

After saving the file, hit Done Now, go back to the wizard and hit Continue

You need to upload this CSR file to Apple’s server Click on the Browse and locate the file on theDesktop Click on Generate See Figure 17.11

After a few seconds, the Apple Push Service (APS) certificate will be generated See Figure 17.12.Now we need to download it so that we install the certificate on our server Click on Download Now

as shown in Figure 17.13

Now, hit Done You’ll see that the Apple Push Notification service for the App ID says Enabled and

it is green See Figure 17.14

Trang 24

Figure 17.9 Filling in the certificate information.

Figure 17.10 Saving the certificate signing request file

Figure 17.11 Locating the certificate signing request file

Installing the SSL certificate on the server

Now that we have the SSL certificate, we need to install it on the server In addition, we need toconfigure the server application so that it uses this certificate when talking with Apple’s notificationservers

Trang 25

Figure 17.12 Successfully generating the SSL certificate.

Figure 17.13 Downloading the SSL certificate

Figure 17.14 An App ID enabled for APS

Double-click on the SSL certificate and install it on the server as shown in Figure 17.15

Figure 17.15 Installing the SSL certificate on the server

Trang 26

Now that the SSL certificate is installed on the server, we need to tell the server about this certificate.

It all depends on the environment in which you wrote the server Here, we are using a simple serverwritten in Objective-C that runs on a Mac You will find this server in thePushMeBaby projectavailable from the source downloads

Rename the SSL.cer file toapns.cerand drag and drop it in the bundle of thePushMeBabyproject as shown in Figure 17.16

Figure 17.16 The apns.cer file referenced in the bundle of the server application

This completes the server configuration One more thing that you need to take care of The first timeyou launch thePushMeBabyserver application, the Mac OS asks you for permission to sign usingyour key You should choose Always Allow as shown in Figure 17.17

Figure 17.17 Giving permission to the server to use the key

Trang 27

17.5.2 Configuring the client

Now that we have configured the server, we need to configure the client

Creating a provisioning profile

We need to create a provisioning profile for our application Go back to the Program Portal andchoose the Provisioning menu as shown in Figure 17.18

Figure 17.18 The Provisioning menu in the Program Portal

Click on Add Profile as shown in Figure 17.19

Figure 17.19 The Add Profile button

Now, you need to fill in a form so that the provisioning profile can be created Choose a name forthis profile, select the certificate, choose the push notification App ID you created and the devicesyou want to install this profile on Click Submit See Figure 17.20

After creating the profile, you will see it available for download and listed under DevelopmentProvisioning Profiles as shown in Figure 17.21

Trang 28

Figure 17.20 Creation of the iPhone development provisioning profile.

Figure 17.21 A ready-to-download iPhone development profile

Installing the provisioning profile on the device and XCode

Now, we need to install the provisioning profile to the device(s) and make XCode aware of it Click

on Download and save the profile on your computer In XCode, choose Windows > Organizer Selectthe device you want to install the profile on as shown in Figure 17.22

Figure 17.22 Selecting the device in Organizer

Drag and drop the provisioning profile to the Provisioning section in Organizer as shown inFigure 17.23

Trang 29

Figure 17.23 The Provisioning section of the device info in Organizer.

Double-click the provisioning profile file in Finder and choose XCode to open it This will makeXCode aware of this profile

Configuring the XCode application

In XCode, change the Bundle Identifier of the application (in the.plistfile) to the one you used

in generating the App ID as shown in Figure 17.24

Figure 17.24 Specifying the Bundle ID of the application in the plist file

Now, we need to configure the target so that XCode builds the application with the correct profile.Double-click on the target as shown in Figure 17.25

Figure 17.25 Specifying the provisioning profile in the target

Select the Build tab and choose the provisioning profile in the Code Signing section as shown inFigure 17.26

Now, you should be able to build and install the application on the device Make sure that you aretargeting the device as shown in Figure 17.27

Trang 30

Figure 17.26 Specifying the provisioning profile in the target.

Figure 17.27 Targeting the device from XCode

17.5.3 Coding the client

Coding the client involves registering for push notification, sending the device token to the server,and responding to notification messages

Registering for push notification

The push-enabled application is required to register for remote notification on startup You usually

do that in theapplicationDidFinishLaunching:method as shown below:

- (void)applicationDidFinishLaunching:(UIApplication *)application {[[UIApplication sharedApplication] registerForRemoteNotificationTypes:

UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert];

}

Trang 31

TheregisterForRemoteNotificationTypes:method takes an integer whose bits specify therequest for accepting a given notification type This method is declared as follows:

Figure 17.28 An alert view asking the user to approve notifications for a given application

If the user approves the action and the registration is successful, the methodRegisterForRemoteNotificationsWithDeviceToken:gets called

application:did-You get the device token in the second parameter The following shows a sample implementationthat just logs the token:

Trang 32

- (void)application:(UIApplication *)application

didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)token{NSLog(@"Inform the server of this device token: %@", token);

}

The device token remains constant for a given application Your application should send the token

to the server so that the device can be targeted for future notifications

If the registration fails, the methodtionsWithError:gets called with the error The method is declared as follows:

The contents of theuserInfodictionary will be as follows:

2009-04-12 21:02:29.870 TestingAPNS[92:107] The user info: {

Trang 33

Figure 17.29 An alert displaying a notification message.

17.5.4 Coding the server

The server is required to generate a JSON dictionary with information about what message to besent, what the number is that should be stored as a badge on the application icon, and the name ofthe sound that needs to play should the application happen to be inactive

Coding for the server is beyond the scope of this text You can look at an example in thePushMeBabyproject available in the source downloads

17.6 Sending Email

To send email from within your iPhone application, you can choose one of the following fourapproaches:

• Use the standard email interface This approach allows you to set up the initial configuration

of a new email message You can pre-fill the recipients, the subject, and any attachments youwant After that, you present the standard email interface to the user The user can edit theemail fields and possibly change your initial values The user can then send or cancel theemail altogether

• Use a back-end service Using this approach, you send the email fields to the server and the

server then sends the email

Trang 34

• Use theUIApplication openURL:method You can set up a URL with the encoded email

message and invoke theopenURL:static method of theUIApplicationclass Using thisapproach will result in your application quitting and theMail.appapplication being launchedwith a new message This approach does not allow for file attachment

• Use an SMTP library Simple Mail Transfer Protocol (SMTP) is a protocol used to send

email over the Internet Using this approach you utilize SMTP to send the email from theiPhone without the user’s intervention

In this section, we discuss the first approach

17.6.1 Using the mail composition view controller

The classMFMailComposeViewControlleris used to show an email interface that the user caninteract with You create an instance of this controller, initialize it, configure the different email fieldsand present it to the user modally

Checking email capability

Before you do all that, you need to check whether your application can send the email You checkthat by using the following static method:

+ (BOOL)canSendMail

Creating the email composition controller

If you can send the email, you can proceed to create the mail controller as shown below:

MFMailComposeViewController *mailCtrl =

[[[MFMailComposeViewController alloc] init] autorelease];

Adding the subject line

Once it is created, you can add a subject line using thesetSubject:method which is declared asfollows:

- (void)setSubject:(NSString *)subject

This method takes a string as an argument and uses that string to set theSubjectheader of theemail message The user can later modify this value

Ngày đăng: 13/08/2014, 18:20

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN