Mobile Retailing - iPhone - PDF version
1
End-to-End Mobile Reference Applications
Mobile Retailing - iPhone - PDF version
© Copyright 2013 SAP AG or an SAP affiliate company. All rights reserved.
No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be changed without prior notice.
Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. National product specifications may vary.
These materials are provided by SAP AG and its affiliated companies ("SAP Group") for informational purposes only, without
representation or warranty of any kind, and SAP Group shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP Group products and services are those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty.
SAP and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and other countries. Please see http://www.sap.com/corporate-en/legal/copyright/index.epx#trademark for additional trademark information and notices.
This tutorial intends to complement SAP product documentation. While specific product features and procedures typically are explained in a practical business context, it is not implied that those features and procedures are the only approach in solving a specific business problem using SAP NetWeaver. Should you wish to receive additional information, clarification or support, please refer to SAP Consulting.
Any software coding and/or code lines / strings (“Code”) included in this documentation are only examples and are not intended to be used in a productive system environment. The Code is only intended better explain and visualize the syntax and phrasing rules of certain coding. SAP does not warrant the correctness and completeness of the Code given herein, and SAP shall not be liable for errors or damages caused by the usage of the Code, except if such damages were caused by SAP intentionally or grossly negligent. Disclaimer:
Some components of this product are based on Java™. Any code change in these components may cause unpredictable and severe malfunctions and is therefore expressively prohibited, as is any decompilation of these components.
Any Java™ Source Code delivered with this product is only to be used by SAP’s Support Services and may not be modified or altered in any way.
Mobile Retailing - iPhone - PDF version
3
Contents of this Tutorial
Introduction 1. Installations
2. Development of the iPhone Mobile Retailing app 3. Deploy and run the application
Mobile Retailing - iPhone - PDF version
Introduction
What do you get here?
This end-to-end tutorial offers a walk through of an iPhonr based Mobile Retailing application for any developer. This application is based on the Enterprise Procurement Model (EPM).
It guides you through the ready-to-run Mobile Retailing development scenario which includes: Set up of your Development Environment from scratch (Section 1)
Setting up the Application on SMP(SAP Mobile Platform, enterprise edition, cloud version) and Gateway services (Section 2) Retrieval of data using SMP from an ABAP backend using OData Services (Section 3)
Deploy and run the Mobile Retailing application on an iPhone device (Section 3)
Scenario Overview
Architecture of the iPhone Mobile Retailing Application
Scenario Walk through Details
In this scenario a customer can browse through a list of available products, view its details and then shop for the products online using a mobile device.
Mobile Retailing - iPhone - PDF version
5
Now you can try out the tutorial by executing the steps of the following sections: Section 1: Various installation details required to develop the app
Section 2: Steps to download the source code and setup the Application on SAP Mobile Platform cloud Section 3: Steps to deploy and run the application on an iPhone device
Mobile Retailing - iPhone - PDF version
1. Installations
1.1 Xcode
1.2 Register for SAP HANA Cloud Developer Account
1.1 Xcode
Xcode is Apple's free gcc based IDE for OS X. You can download it from the Apple Developer Center, though you have to be registered as an apple developer.
Download the latest version of Xcode.
Mobile Retailing - iPhone - PDF version
7
It will start copying Xcode to your Applications folder.Click "Open".
Mobile Retailing - iPhone - PDF version
Mobile Retailing - iPhone - PDF version
9
Mobile Retailing - iPhone - PDF version
1.
2. 3. 4.
1.2 Register for SAP HANA Cloud Developer Account
For developing and running Web applications on SAP HANA Cloud you have to register once for a Cloud Developer Account. Execute the following steps to register for your own Cloud Developer Account.
Open [https://account.hanatrial.ondemand.com]
Choose Register to open a registration form.
On the registration form enter the corresponding fields, read the Terms of use and then select the option that you have read and understand the Terms and Conditions of SAP HANA Cloud.
Mobile Retailing - iPhone - PDF version
11
4.5.
6.
A registration confirmation message appears. An e-mail which contains the activation link of your cloud developer account will be sent to you.
Mobile Retailing - iPhone - PDF version 6. 7. 8. 9. 10.
Choose the Click here to activate your account button and an Account Successfully Activated message will appear. Choose Continue to launch the SAP HANA Cloud Cockpit of your newly created developer account.
As you launch your Cloud Cockpit the first time you have to decide which type of database your account should use.
Choose SAP HANA Database as Default Database Type for your newly created developer account and choose Continue. A successfully created Developer Account message appears.
Mobile Retailing - iPhone - PDF version
13
10.11.
12.
Confirm with OK to open your SAP HANA Cloud Cockpit
A welcome page for the SAP HANA Cloud is displayed. Choose SAP Mobile Platform, enterprise edition, cloud version to go to your Mobile platform admin page.
If a welcome page is not displayed you can still navigate to your SAP Mobile Platform Admin page by Clicking Services and then SAP Mobile Platform enterprise edition, cloud version.
Mobile Retailing - iPhone - PDF version 12.
13. Then you will see the initial Mobile platform Admin page for your developer account.
As the arrow on the left side indicates there are no applications so far in your developer account. No wonder, you‘ve just created it.
Remember the URL as you will need it later. In the header of the cloud cockpit you find the important info of your SAP HANA Cloud trial developer account name of form "<P-USER>trial" (p-user with lower case).
Remember your Account Data
After executing successfully the above described account creation steps you have your SAP HANA Cloud (Trial) Developer Account with the following three parameters which you might need later several times in this or other tutorials:
SAP HANA Cloud Developer Account name: "<your P-User>trial" (p-user with lower case) (SCN) user name: <your P-User> (alternatively <e-mail> as user)
(SCN) user account password: <********>
By means of this account you will publish and run the developed mobile Application in your SAP HANA Cloud developer account as described later in this tutorial.
During the SAP HANA Cloud Developer Account creation an SCN user account has been created with which you can deploy your mobile applications to your HANA Cloud Trial developer account. But you can also log on to SAP
where e.g. developers share their knowledge or ask questions in the
Mobile Retailing - iPhone - PDF version
15
2. Development of the iPhone Mobile Retailing app
2.1 NetWeaver Gateway Service (OData)
2.2 Setup the application on SAP Mobile platform, enterprise edition, cloud version for your trial account created in section 1.2 above.
2.3 Import the source code into your local development environment
Once we have all the required user permissions and setup as mentioned in the sections above we are ready to configure the Cloud and our development environment.
2.1 NetWeaver Gateway Service (OData)
There are 2 ways available for consuming OData Service for the App. Either use the existing Public Gateway Services that we provide as mentioned below in Section 2.1.1 or create your own Gateway services using free trial account as mentioned in Section 2.1.2.
2.1.1 Use the existing Public Gateway services
We already have some publicly available gateway services which can be used directly by you. These services are based on the Enterpriese Procurement Model EPM
The service that we are going to use can be accessed on this location
Username: ESPM_TEST Espm1234 Password:
Mobile Retailing - iPhone - PDF version
1.
Terms of Use
The OData service of both backend systems ABAP and HANA Cloud shall only be used for test purposes of the described development
scenario.
The OData service must not be used in any productive application.
It is planned to reset the systems once a week and there is no guarantee that the system is always available.
2.1.2 Create your own Gateway services
Free Trial Editions of SAP NetWeaver Application Server ABAP 7.4 are available in SCN. Please refer the the Link about using the free trial editions. The document talks about the setup and running of the ABAP 7.4 trial instances.
You can use these free trial editions to build your own OData services. You can use the Enterprise Procurement Model(EPM) model as your demo data. This model is part of every SAP NetWeaver ABAP server from 7.02.
Please refer the Link for detailed tutorial on developing the OData services.
2.2 Setup the application on SAP Mobile platform, enterprise edition, cloud version
for your trial account created in section 1.2 above.
Goto your Admin page for the SMP trial account (the URL should look something like this
). Once it is loaded click on the Applications box as shown in the
https://smp-p1934701296trial.hanatrial.ondemand.com/Admin
Mobile Retailing - iPhone - PDF version
17
1.2.
3.
The Applications tab will open where you can review the list of applications. Click on the New button to start configuring your application.
Enter the following details for ID and Name boxes, ID: MobileRetailing, Name: Mobile Retailing Application. You can leave the other fields blank. Click the Save button.
Mobile Retailing - iPhone - PDF version 3.
4.
5.
The Application detail popup will show, here we need to configure the Backend as well as the Authentication tab. The Backend tab should be selected by default. Enter this URL as the endpoint
'http://54.225.119.138:50000/sap/opu/odata/IWBEP/EPM_DEVELOPER_SCENARIO_SRV/'. Select Internet checkbox. This tells the SAP Mobile platform (SMP) that your endpoint is publicly available in the Internet.
Mobile Retailing - iPhone - PDF version
19
5. a. b. c. d. e. f. 6. 7.Enter MobileRetailingSC as the Security Profile Name.
Select the checkbox Enable CAPTCHA. This will require all onboarding requests to be validated using a CAPTCHA challenge.
Select Basic Authentication as the Authentication type.
Enter 'http://54.225.119.138:50000/sap/opu/odata/IWBEP/EPM_DEVELOPER_SCENARIO_SRV/' as the .
Authentication URL Select Internet. Click the Save button.
Confirm the application update in the popup dialog.
Mobile Retailing - iPhone - PDF version 7.
8.
9.
Now we need to configure a separate connection for loading the product images. This step is required as the images are not present in the same path as our OData services. Click on the Settings tab.
Mobile Retailing - iPhone - PDF version
21
9.10.
11.
You should be able to see a backend connection already existing which corresponds to the end point for your application. Click the New button.
Mobile Retailing - iPhone - PDF version 11. a. b. c. d. 12.
Enter MobileRetailingImage as the Connection Name.
Enter http://54.225.119.138:50000/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/ as the Endpoint. Select Internet.
Click Save button.
You should be able to see the connection for your Images. With this step our configuration on the cloud is ready for use.
2.3 Import the source code into your local development environment
Download the source code from this link Mobile Retailing and extract the zip file.Once our application is configured on the cloud we are ready to deploy the iOS code of iPhone app on our local development environment and test with the public Gateway services.
Mobile Retailing - iPhone - PDF version
23
Open the "RetailCloud.xcodeproj".
Although the project is available to be deployed, make sure that the basic configurations are done as mentioned below.
1. In the X-code select the go to the Build Settings Tab -> Select Architectures tab, and set Base SDK for All Configurations to IOS 5.0 (or above) based on the version of x-code.
2. Select the Deployment tab and set the IOS Deployment Target to IOS 5.0 or above, as appropriate for the device version where you will deploy.
3. Select the following:
Mobile Retailing - iPhone - PDF version
Architectures = Standard (armv7,armv7s,i386) Targeted device family = iPhone.
4. Add the following frameworks from the SDK to your project by clicking on the active target, and selecting Build Phase > Link Binary with Libraries. Click on the + button and select the following binaries from the list:
SystemConfiguration.Framework Security.Framework uatzCore.Framework MobileCoreServices.Framework MessagUI.Framework CoreFoundation.Framework CFNetwork.Framework libicucore.A.dylib libstdc++.dylib libz.1.2.5.dylib
5. From the menu select Product > Clean and then Product > Build to test the initial set up of the project. If you have correctly followed this procedure, you should receive a Build Succeeded message.
Mobile Retailing - iPhone - PDF version
25
3. Deploy and run the application
3.1 Running Your App in iOS Simulator 3.2 Run the application on IOS device
3.1 Running Your App in iOS Simulator
When testing an app in iOS Simulator, it is easiest to launch and run your app in iOS Simulator directly from your Xcode project. To run your app in iOS Simulator, choose iPhone 6.0 Simulator from the Xcode scheme pop-up menu, and click Run. Xcode builds your project and then launches the most recent version of your app running in iOS Simulator on your Mac’s screen.
Here you need to provide your Cloud account URL and application names. The settings provided by default corresspond to the landscape already setup by us so you can use these settings also.
Mobile Retailing - iPhone - PDF version
1. 2. 3.
Enter your base Cloud URL ( that is the Admin page URL without Admin) in the first box. Enter MobileRetailing as Application
Enter MobileRetailingImage as Image Connection
Mobile Retailing - iPhone - PDF version
27
If your login is successful you should be able to see the list of categories and follow the scenario as explained in the start of this document.
Mobile Retailing - iPhone - PDF version
1. 2. 3. 4.
3.2 Run the application on IOS device
To run your app on an iOS device during development, it must be connected to your Mac, enabled for development, and recognized by Apple. You do this by providing some information about the app, yourself, and the device. You create a type of signing certificate, called a development certificate, to identify yourself. All of this information is incorporated into a development provisioning profile that is installed and that allows the app to launch on the device.
The easiest way to provision your devices for development is with Xcode. You can sign in to your account and view all the provisioning profiles and signing certificates for your account. Xcode provides a default iOS Team Provisioning Profile and iOS Wildcard App ID for you. Xcode automatically updates this provisioning profile when new development certificates or device IDs are added to your account. The iOS Team Provisioning Profile uses the iOS Wildcard App ID that matches all apps developed by you or your team. The iOS Team Provisioning Profile allows you to begin running the app on a device immediately.
To run your app on a device, you will perform these tasks as follow: Request a development certificate.
Add your device to the portal. Code sign your app.
Launch your app on the device
Mobile Retailing - iPhone - PDF version
29
4. Deep dive into the code
HTTP Connection Make GET request Make POST request
Request the captcha challenge
Pass the captcha and register the device Make requests
Parse the response Create a customer
In this tutorial we are not going to explain the full application but some small code snippets which are necessary for communication with the cloud.
HTTP Connection
In order to create connection and download content from url, we have to use the NSURLConnection delegate methods Start Connection Receive Response Receive Data End Connection Error Report
Start Connection
creating an NSURLRequest instance for the URL and then creates an NSURLConnection instance, specifying the request and a delegate.
NSURL *url = [NSURL URLWithString:[urlString
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]]; //Create the request with cache access policy and timeout interval NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/xml, application/atom+xml" forHTTPHeaderField:@"Accept"]; [request setValue:@"application/atom+xml; charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; //Create the connection with the request
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSAssert( urlConnection != nil, @"Failure to create service description connection.");
If NSURLConnection can’t create a connection for the request, initWithRequest:delegate: returns nil.
If the connection is successful, an instance of NSMutableData is created to store the data that is provided to the delegate incrementally.
Receive Response
Mobile Retailing - iPhone - PDF version
content length of the data, MIME type, suggested filename and other metadata provided by the server.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response; int code = [httpResponse statusCode];
if ( code == 200) //i.e. HTTP Status code 200 for request has succeeded {
NSDictionary *headerDict = [httpResponse allHeaderFields]; //Dictionary fields will fetch length, mime type etc.
} }
Protocol specific metadata like headers and status code can be obtained from NSURLResponse subclass.
Receive Data
The didReceiveData: method is mainly for storing the received data from the server and it will help the user as an indication of connection progress
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// newStr is the string variable to store the string value converted from NSData object received from NSURLConnection
newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; }
End Connection
After downloading the request without error, the connection delegate receives the connectionDidFinishLoading: message indicating that there wont be any connection request and NSURLConnection object can be released.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
//Release the connection and the data object [connection release ];
[receivedData release ]; }
if Automatic Reference Counting (ARC) is enabled, then manual release of connection is not necessary.
Error Report
Mobile Retailing - iPhone - PDF version
31
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"Error: %@",error);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if ([error code] == kCFURLErrorNotConnectedToInternet) {
// once we identify the error, we can present a more precise message to the user. NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"No Connection Error"
forKey:NSLocalizedDescriptionKey];
NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:userInfo];
[self handleError:noConnectionError]; }
else
// otherwise handle the error generically [self handleError:error];
}
- (void)handleError:(NSError *)error {
alertView = [[UIAlertView alloc] initWithTitle:@"Error may be due to wrong captcha, WiFi connections,parsing.." message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show];
//exit the app as soon as there is an exception
[self.view setUserInteractionEnabled:NO];
}
After the delegate receives a message connection:didFailWithError:, the connection is closed and no further delegates messages are received .
Make GET request
The following code is used to make all the GET requests
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
[request setHTTPMethod:@"GET"];
Make POST request
The following code is used for making all POST requests
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
Request the captcha challenge
The following code requests the server for registration, which responds with a captcha challenge (if enabled). The response comes to a captcha challenge listener which in turn passes it on the activity for processing.
Mobile Retailing - iPhone - PDF version
NSString *string2 = [txtSmpUrl.text stringByAppendingString:txtAppConnection.text]; //txtSmpUrl.text contains the cloud connection url
string2 = [string2 stringByAppendingString:@"/"]; NSString *string2 = [txtSmpUrl.text stringByAppendingString:txtAppConnection.text];
string2 = [string2 stringByAppendingString:@"/"];
urlSmpString = [[NSString alloc] initWithString:string2 ];
NSString *string3 = [txtSmpUrl.text stringByAppendingString:@"odata/applications/latest/"]; NSString *string4 = [string3 stringByAppendingString:txtAppConnection.text];
NSString *string5 = [string4 stringByAppendingString:@"/Connections"];
urlSmpConnString = [[NSString alloc] initWithString:string5 ];
NSString *string6 = [txtSmpUrl.text stringByAppendingString:txtImageconnection.text];
NSURL *url = [NSURL URLWithString:[urlSmpConnString
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/xml, application/atom+xml" forHTTPHeaderField:@"Accept"]; [request setValue:@"application/atom+xml; charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; //appCid is the unique application connection id
[request setValue:appCid forHTTPHeaderField:@"X-SUP-APPCID"]; [request setValue:@"Fetch" forHTTPHeaderField:@"X-CSRF-TOKEN"]; //Pass the login username and password
NSString *authStr = [NSString stringWithFormat:@"%@:%@", gwUserTxt, gwPasswordTxt]; NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedString]]; [request setValue:authValue forHTTPHeaderField:@"Authorization"];
NSMutableData *postData = [[xmlString dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
[request setHTTPBody:postData];
The captcha challenge processing in (NSURLConnection *)connection didReceiveData: method
newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *strData = [[NSData alloc] initWithData:[NSData dataWithBase64EncodedString:newStr]]; imageCaptcha = [UIImage imageWithData:strData];\\imageCaptcha is UIImage object
Pass the captcha and register the device
Once the user has decoded the captcha we have to pass it back to the server for validation. Also we need to request the registration. If the response is HTTP 201 it means the application connection was created successfully.
Mobile Retailing - iPhone - PDF version
33
NSURL *url = [NSURL URLWithString:[urlSmpConnString
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/xml, application/atom+xml" forHTTPHeaderField:@"Accept"]; [request setValue:@"application/atom+xml; charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; [request setValue:appCid forHTTPHeaderField:@"X-SUP-APPCID"];
//captchaTxt is the captcha vale you have entered
[request setValue:captchaTxt forHTTPHeaderField:@"X-SUP-CAPTCHA-TEXT"]; [request setValue:@"Fetch" forHTTPHeaderField:@"X-CSRF-TOKEN"];
NSString *authStr = [NSString stringWithFormat:@"%@:%@", gwUserTxt, gwPasswordTxt]; NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedString]]; [request setValue:authValue forHTTPHeaderField:@"Authorization"];
NSMutableData *postData = [[xmlString dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
[request setHTTPBody:postData];
NSURLConnection *captchaConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Make requests
Once our device is registered, we are ready to make the HTTP requests to fetch the data from the server using the Application endpoint. As the processing of OData is sequential we start the specific AsyncTask one after the other.
NSString *productSD = [sdDict objectForKey:@"Product"];//Fetching of List of productsNSString *productSD = [sdDict objectForKey:@"Product"];
NSString *productUrl = [proxyApplicationEndpoint stringByAppendingString:productSD]; NSURL *url = [NSURL URLWithString:[urlSmpString
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
[request setHTTPMethod:@"GET"];
[request setValue:productUrl forHTTPHeaderField:@"X-SUP-BACKEND-URL"]; [request setValue:appCid forHTTPHeaderField:@"X-SUP-APPCID"];
Parse the response
If the requests made are successful we can start parsing the received data. Call the corresponding NSXMLParser Delegates for parsing the document
If the parser encounters an error, it stops parsing and invokes the delegation method parser:parseErrorOccurred: to interpret the error and inform the user.
NSString *xmlVal = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; //convert the received data that is from NSURLConnection delegate method to UTF-8 encoding
NSData *responseData = [xmlVal dataUsingEncoding:NSUTF8StringEncoding]; [parser setDelegate:self];
[parser setShouldProcessNamespaces:NO]; [parser setShouldReportNamespacePrefixes:NO]; [parser setShouldResolveExternalEntities:NO];
[parser parse]; // if not successful, delegate is informed of error [parser parserError];
Mobile Retailing - iPhone - PDF version
In your View Controller implementation (.m) file , Declare and allocate memory for the variables
In the implementation file, load the data from the webservice that is to be parsed and the element “href” of attribute data of tag “<app-collection>”and the element “sap-member-title” can be handled in the example below when the parser encounters the start tag of the element.
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
self.attrDict = attributeDict;
if ([elementName isEqualToString:@" sap-member-title "]) {
// member is an instance variable to stor e the member property member= [[NSString alloc] init];
return; }
//Handling the attrbute of the element ([elementName isEqualToString:@ ])
if "app:collection"
{
NSString *href = [self.attrDict objectForKey:@"href"];//Here the attributes of the <app-collection> will stored in a Dictionary object
(href)
if
[sdObjects addObject:href];//sdObjects is an NSDictionary to store key value property of href attribute
}
storingCharacterData = [elementsToParse containsObject:elementName]; }
Responses for other entity elements are also done in a similar fashion.
Create a customer
All previous requests dealt with fetching the data from the server. Now will see how to create a request to send some data to the server. In this example we will see how the customer is created on the server using a POST request.
Mobile Retailing - iPhone - PDF version
35
//xmlStringBP is the post body
xmlStringBP= [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"
"<entry xml:base=\"http: //ldcigiq.wdf.sap.corp:50015/sap/opu/odata/IWBEP/EPM_RETAIL_SCENARIO_SRV/\" xmlns:d=\" http://schemas.microsoft.com/ado/2007/08/dataservices\" xmlns:m=\" http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\" xmlns=\" http://www.w3.org/2005/Atom\">\r\n" text\
"<title type=\" ">BusinessPartners('')</title>\r\n"
"<category term=\"ZEPM_RETAIL_SCEN_TMP_SRV_01.Businesspartner\" scheme=\"http: //schemas.microsoft.com/ado/2007/08/dataservices/scheme\" />\r\n"
BusinessPartners('')\ edit\ Businesspartner\
"<link href=\" " rel=\" " title=\" " />\r\n"
"<content type=\"application/xml\">\r\n"
"<m:properties>\r\n" "<d:CustomerId />\r\n" "<d:DateOfBirth>2023-07-01T00:00:00.0000000</d:DateOfBirth>\r\n" "<d:EmailAddress>%@</d:EmailAddress>\r\n" "<d:PhoneNumber>%@</d:PhoneNumber>\r\n" "<d:City>%@</d:City>\r\n" "<d:Street>%@</d:Street>\r\n" "<d:PostalCode>%@</d:PostalCode>\r\n" "<d:Country>IN</d:Country>\r\n" "<d:FirstName>%@</d:FirstName>\r\n" "<d:LastName>%@</d:LastName>\r\n" "</m:properties>\r\n" "</content>\r\n" "</entry>\r\n" ,email,phone,address,address,zip,name,name];
NSString *busPartner = [sdDict objectForKey:@"Customer"];
NSString *busPartnerUrl = [proxyApplicationEndpoint stringByAppendingString:busPartner];
NSURL *url = [NSURL URLWithString:[urlSmpString
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSMutableData *postData = [[xmlStringBP dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
[request setHTTPBody:postData];
On request completion we check the HttpResponse object, if its HTTP 201 the customer was successfully created in the backend. The response body contains the Customer details which we can parse using the following code
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if (storingCharacterData) {
NSString *trimmedString = [workingPropertyString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; [workingPropertyString setString:@""]; // clear the string for next time
([elementName isEqualToString:@ ])
if "d:CustomerId"
{
NSLog(@"Business Partner ID : %@",trimmedString ); BP_ID = trimmedString ;//BP_ID is customer id }
} }