Getting data from server in objective c class - objective-c

Im trying to make a class where when I create an instance of that class and pass a username and password to the class it sends it to the server and gives whether its a valid password or whether theres an error. When I try to access the response variable from the instance I get null. I suspect that the methods begin called -(void)connectionDidFinishLoading:(NSURLConnection *)connection is happening before the variable is being accessed. Is there a better way to access the variable or call the method so it happens before the variable is accessed
Login View Controller.h
#interface LoginViewController : UIViewController
-(IBAction)Login:(id)sender;
#property (nonatomic, retain) IBOutlet UITextField *username;
#property (nonatomic, retain) IBOutlet UITextField *password;
#end
Login View Controller.m
#import "LoginViewController.h"
#import "Users.h"
#interface LoginViewController ()
#end
#implementation LoginViewController
#synthesize username, password;
/*
-(IBAction)Login:(id)sender{
Users *user = [[Users alloc] init];
[user Login:username.text :password.text];
if ([user.serverResponse isEqual: #"Status:Created"]) {
[self performSegueWithIdentifier:#"home" sender:nil];
}
else{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#""
message:#"Username or Password is incorrect"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
[alert show];
}
NSLog(#"%#",user.serverResponse);
}
#end
Users Class.h
#import <Foundation/Foundation.h>
#interface Users : NSObject
- (void)Login:(NSString*)username :(NSString*)password;
- (void)Signup:(NSString*)username :(NSString*)password :(NSString*)password_confirmation :(NSString*)email;
#property (nonatomic, retain) NSMutableData *response;
#property (nonatomic, retain) NSString *serverResponse;
#end
Users Class.m
#import "Users.h"
#define loginURL #"linktoserver"
#define signupURL #"linktoserver"
#implementation Users
#synthesize response, serverResponse;
- (void)Login:(NSString*)username :(NSString*)password{
NSMutableData *data = [[NSMutableData alloc] init];
self.response = data;
NSURL *url = [NSURL URLWithString:loginURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
// Http Method
[request setHTTPMethod:#"POST"];
// Intializes Post Data
NSString *postData = [NSString stringWithFormat:#"username=%#&password=%#", username, password];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
// Intializes Connection Request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
#pragma Connection
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
[response appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
serverResponse = [[NSString alloc] initWithData:response
encoding:NSUTF8StringEncoding];
}

Use NSURLSession instead of NSURLConnection with delegates (to simplify the process):
[[[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error && data){ // here you can check also response.statusCode if needed
NSString *serverResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(), ^{
completion(serverResponse);
});
}else {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil);
//show some alert about no connection etc
});
}
}] resume];
add completion to your method
- (void) login:(NSString*)username
password:(NSString*)password
completion:(void (^)(NSSring *response))completion
and then compare response in the completion in the loginViewController
[user login:#"aaa" password:#"bbb" completion:^(NSString *response) {
if ([response isEqualToString:#"ccc"]){
// success!
}else{
// alert
}
};

Related

objective c completion handler

I have RequestManager class with getContentInBackgroundWithMemberId and postRequest functions. I want to call them from my view controller and get result using completion handler. How to edit my functions?
RequestManager.h
#import <Foundation/Foundation.h>
#interface RequestManager : NSObject
-(void)getContentInBackgroundWithMemberId:(int)memberId;
#end
RequestManager.m
#import "RequestManager.h"
#implementation RequestManager
-(void)postRequestWithParams:(NSDictionary*)params
{
NSString *parameters = #"encrypt=93mrLIMApU1lNM619WzZje4S9EeI4L2L";
for(id key in params)
{
NSString *obj = [NSString stringWithFormat:#"&%#=%#",key,[params objectForKey:key]];
[parameters stringByAppendingString:obj];
}
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://someserver"]];
NSData *postBody = [parameters dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postBody];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if(!connectionError)
{
NSDictionary *serverData =[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *result = [NSArray array];
result = [serverData objectForKey:#"result"];
}
}];
}
-(void)getContentInBackgroundWithMemberId:(int)memberId
{
NSDictionary *params = [NSDictionary dictionary];
params = #{#"member_id":[NSNumber numberWithInt:memberId]};
[self postRequestWithParams:params];
}
#end
ViewController.h
#import <UIKit/UIKit.h>
#import "RequestManager.h"
#interface ViewController : UIViewController
#property (strong,nonatomic) RequestManager *requestManager;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
int memberId = 82;
//here i want to call getContentInBackgroundWithMemberId and get result using completion handler;
_requestManager = [[RequestManager alloc]init];
[_requestManager getContentInBackgroundWithMemberId:memberId];
}
#end
RequestManager.h
#interface RequestManager : NSObject
//Create a block property
typedef void(^postRequestBlock)(BOOL status);
-(void) getContentInBackgroundWithMemberId: (int) memberId completed:(postRequestBlock)completed;
#end
RequestManager.m
-(void) getContentInBackgroundWithMemberId: (int) memberId completed:(postRequestBlock)completed{
NSDictionary * params = [NSDictionary dictionary];
params = # {
# "member_id": [NSNumber numberWithInt: memberId]
};
[self postRequestWithParams: params completed:^(BOOL status){
completed(status);
}];
}
//Add completion block.
-(void) postRequestWithParams: (NSDictionary * ) params completed:(postRequestBlock)completed{
[NSURLConnection sendAsynchronousRequest: request queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (!connectionError) {
NSDictionary * serverData = [NSJSONSerialization JSONObjectWithData: data options: 0 error: nil];
NSArray * result = [NSArray array];
result = [serverData objectForKey: # "result"];
completed(YES);
} else {
completed(NO);
}
}];
}
There are already tons of Q&A's for blocks. Here's one that might help further explain
How to write an Objective-C Completion Block

capture a variable content and pass it to a second view controller

I have read so much on the subject of passing variable between ViewController in Xcode I am totally lost.
1:I have a members database on my server which is populated with members details
2: In xcode a have a "ViewController.h and .m" which run code allowing users to authenticate with the members data table on my sever. This works perfectly well, no issues.
What I want to do is capture the "login" and "password" into two variables and use the variables in a second "ViewController".
First ViewController.h:
#interface FirstViewController : UIViewController {
UITextField *txtUsername;
UITextField *txtPassword;
}
#property (nonatomic, retain) IBOutlet UITextField *txtUsername;
#property (nonatomic, retain) IBOutlet UITextField *txtPassword;
- (IBAction)loginClicked:(id)sender;
- (IBAction)backgroundClick:(id)sender;
First ViewController.m
#import "FirstViewController.h"
#import "WebViewController.h"
#import "SBJson.h"
#implementation FirstViewController
#synthesize txtPassword, txtUsername;
- (IBAction)loginClicked:(id)sender {
#try {
if([[txtUsername text] isEqualToString:#""] || [[txtPassword text] isEqualToString:#""] ) {
[self alertStatus:#"Please enter both Username and Password" :#"Login Failed!"];
} else {
NSString *post =[[NSString alloc] initWithFormat:#"login=%#&pass=%#",[txtUsername text],[txtPassword text]];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://www.mydomain.com/check1.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %d", [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(#"%#",jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"success"] integerValue];
NSLog(#"%d",success);
if(success == 1)
{
//NSLog(#"Login SUCCESS");
//[self alertStatus:#"Logged in Successfully." :#"Login Success!"];
WebViewController *second = [[WebViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:second animated:YES];
} else {
NSString *error_msg = (NSString *) [jsonData objectForKey:#"error_message"];
[self alertStatus:error_msg :#"Login Failed!"];
}
} else {
if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#"Login Failed!"];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Login Failed." :#"Login Failed!"];
}
}
Second ViewController.h
#interface LettoWebViewController : UIViewController {
IBOutlet UIWebView *lettoWebView;
NSString *AmemberUsername;
NSString *AmemberPassword;
}
#property (retain) NSString *AmemberUsername;
#property (retain) NSString *AmemberPassword;
Second ViewController.m
#import "WebViewController.h"
#import "SBJson.h"
#interface WebViewController ()
#end
#implementation WebViewController
#synthesize AmemberPassword, AmemberUsername;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSString *post =[[NSString alloc] initWithFormat:#"login=%#&pass=%#",[AmemberUsername text],[AmemberPassword text]];
NSLog(#"PostData: %#",post);
NSURL *myURL=[NSURL URLWithString:#"http://www.mydomain.com/apps/index.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:myURL];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[lettoWebView loadRequest:request];
}
My questions is; how can I can I pass the two variables in the most simple way.
Any help would be great but please be kind I am very new to xcode and coding in general.
Regards
DJ
The solution:
When you created WebViewController, you just had to set the two parameters.
WebViewController *second = [[WebViewController alloc] initWithNibName:nil bundle:nil];
[second setAmemberUsername:[txtUsername text]];
[second setAmemberPassword:[txtPassword text]];
[self presentModalViewController:second animated:YES];
In your viewDidLoad of the WebViewController:
There was an issue, you wrote:
NSString *post =[[NSString alloc] initWithFormat:#"login=%#&pass=%#",[AmemberUsername text],[AmemberPassword text]];
But, AmemberPassword and AmemberUserName are NSString. So they don't know the text method. They aren's UITextField.
So the correction is:
NSString *post =[[NSString alloc] initWithFormat:#"login=%#&pass=%#",AmemberUsername,AmemberPassword];

HTTPS data returned not saving

I have an object class set up called WebCalls. In this class, I make a web call and return some JSON from an HTTPS server. Now the methods work perfectly, I have tested and the data returns fine. However my problem is, I can't access the data returned outside the class.
The code to retrieve the data is below
Interface
#interface WebCall : NSObject{
NSString *phoneNumber;
NSString *jsonData;
}
#property (nonatomic, retain) NSMutableData *responseData;
#property (nonatomic, retain) NSString *jsonData;
-(void) getData: (NSString *) link;
#end
Implementation
#implementation WebCall
#synthesize jsonData;
#synthesize responseData;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
self.responseData = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *s = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
jsonData = s;
}
-(void) getData: (NSString *) link{
jsonData = [[NSString alloc] init];
self.responseData = [NSMutableData data];
NSURL * url = [NSURL URLWithString:link];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"GET"];
[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
}
#end
In interface class I have a string called jsonData. I get and set it using property and synthesise. So after I make web call, I assign the data to jsonData, and I should be able to import web call class, use the getInfo method, have the jsonData returned and then access it using
WebCall *wc = [[WebCall alloc] init];
[wc getData:url];
NSLog(#"%#", [c jsonData]);
However this just prints out null. And yet if I print out the String in the Webcall class after I recieve the data, it prints out fine. Could anyone tell me what I am doing wrong?
Thanks in advance
Edit: Updated with complete implementation
Also I can't access the string outside the method. I copied the code to another class, and tried assigning the JSON String, then calling it again in the body, and it comes out null again. Seems I can only print it out in that connection method. Then it seems to clear the String
Edit: What I tried
[wc setWebCallDidFinish:^(NSString * json, NSString *test){
NSLog(#"%#", json);
}];
[wc getData:#"12345"];
Adam the reason jsonData is an empty string is because [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES]; runs asynchronously which means on a new thread and it doesn't block. this means that when you call [wc getData:url]; and then immediately call NSLog(#"%#", [wc jsonData]); the http request hasn't completed yet and the - (void)connectionDidFinishLoading:(NSURLConnection *)connection delegate function hasn't been called yet in your WebCall.
For a detailed explanation read this iOs Concurrency Programming Guide. Essentially you need to add a notifier to your WebCall so that it can notify the object which spawns it that the request has finished loading. I would use a block like so.
#interface WebCall : NSObject{
NSString *phoneNumber;
NSString *jsonData;
void(^webCallDidFinish)(NSString *jsonData, id otherRandomVar);
}
#property (nonatomic, retain) NSMutableData *responseData;
#property (nonatomic, retain) NSString *jsonData;
-(void) getData: (NSString *) link;
-(void)setWebCallDidFinish:(void (^)(NSString *, id))wcdf;
#end
Implementation
#implementation WebCall
#synthesize jsonData;
#synthesize responseData;
-(void)setWebCallDidFinish:(void (^)(NSString *,id))wcdf{
webCallDidFinish = [wcdf copy];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *s = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
jsonData = s;
webCallDidFinish(jsonData, #"any other object");
}
//all of your other code here
Then in the calling code the following
WebCall *wc = [[WebCall alloc] init];
[wc setWebCallDidFinish:^(NSString * json, id randomSecondVar) {
NSLog(#"%#",json);
}];
[wc getData:url];
What will happen is the block of code you provide to setWebCallDidFinish will be called after jsonData is loaded. You could also use the Delegate pattern to accomplish this. Note that while this asynchronous request is loading you should provide some sort of indicator to your user.

How to get an array from NSMutableData

I have text file with 5 strings. I need to use NSURLConnection to get contnent of this file. But NSLog shows me, that 'dump' is empty. How can I transform the data from NSMutableData to NSArray. Arrays is because I need to show those 5 items in a TableView.
NSURLRequest *theRequest=[NSURLRequest
requestWithURL:[NSURL URLWithString:#"http://dl.dropbox.com/u/25105800/names.txt"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
receivedData = [NSMutableData data];
NSString *dump = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
NSLog(#"data: %#", dump);
NSArray *outputArray=[dump componentsSeparatedByString:#"\n"];
self.namesArray = outputArray;
Thanks in advance. BTW URL works, you can see the file.
Here's how you implement this solution with a delegate:
In your .h file:
#interface MyClass : NSObject <NSURLConnectionDelegate, NSURLConnectionDataDelegate>
#property (nonatomic, retain) NSMutableData *receivedData;
#property (nonatomic, retain) NSArray *namesArray;
#end
In you .m file:
#implementation MyClass
#synthesize receivedData = _receivedData;
#synthesize namesArray = _namesArray;
- (id)init {
self = [super init];
if (self) {
self.receivedData = [NSMutableData data];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://dl.dropbox.com/u/25105800/names.txt"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[connection start];
}
return self;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"Received response! %#", response);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *dump = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
NSLog(#"data: %#", dump);
self.namesArray = [dump componentsSeparatedByString:#"\n"];
}
#end
If you don't want to use a delegate, you can use a synchronous call with NSURLConnection, like this:
NSURLRequest *theRequest=[NSURLRequest
requestWithURL:[NSURL URLWithString:#"http://dl.dropbox.com/u/25105800/names.txt"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSError *error = nil;
NSHTTPURLResponse *response = nil;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:theRequest response:&response error:&error];
if (error == nil) {
NSString *dump = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
NSLog(#"data: %#", dump);
NSArray *outputArray=[dump componentsSeparatedByString:#"\n"];
self.namesArray = outputArray;
}
Just beware that this will not be running asynchronously. If you don't want it to run on the main thread and block your main thread/UI, consider using a separate thread to execute that code or use GCD.
You have to use the delegate, then save the received data into receivedData (which is of course empty right now.. you just initalized it.) and then you transform the data into a string, like you did it in your example. Have a look at NSURLConnectionDelegate
You need to implement the delegate methods for NSURLConnection to be notified of incoming data. You are using the asynchronous methods.
Also note that [NSMutableData data] just creates an empty data-object.. so you can't expect it to contain any data..
I suggest you read https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE
(completely!)

Xcode is not calling asp.net webservice

I have oracle database and using webservice i want to insert some records in to it
So i created webservice in asp.net as follows
public bool PickPill(string Me_id, string Mem_device_id, string Test_datetime, string Creation_id, string PillBayNo)
{
string Hed_seq_id = Hed_seq_Id();
bool ResultHED = InsHealthEData(Hed_seq_id, Mem_device_id, Me_id, Test_datetime, Creation_id);
bool ResultHET = InsHealthETest(Hed_seq_id, PillBayNo, Test_datetime, Creation_id);
if (ResultHED == ResultHET == true)
return true;
else
return false;
}
this function did all data insertion trick for me i tested this service on the local mechine with ip address
http:72.44.151.178/PickPillService.asmx
then,
I see an example on how to attach asp.net web service to iphone apps
http://www.devx.com/wireless/Article/43209/0/page/4
then i created simillar code in xcode which has 2 files
ConsumePillServiceViewController.m
ConsumePillServiceViewController.h file
Now,
Using Designer of xcode i created 5 textboxes(Me_id,Mem_device_id,Test_datetime,Creation_id,PillBayNo) with all parameters hardcode as our service demands
then modify my ConsumePillServiceViewController.h file as follows
#interface ConsumePillServiceViewController : UIViewController {
//---outlets---
IBOutlet UITextField *Me_id;
IBOutlet UITextField *Mem_device_id;
IBOutlet UITextField *Test_datetime;
IBOutlet UITextField *Creation_id;
IBOutlet UITextField *PillBayNo;
//---web service access---
NSMutableData *webData;
NSMutableString *soapResults;
NSURLConnection *conn;
}
#property (nonatomic, retain) UITextField *Me_id;
#property (nonatomic, retain) UITextField *Mem_device_id;
#property (nonatomic, retain) UITextField *Test_datetime;
#property (nonatomic, retain) UITextField *Creation_id;
#property (nonatomic, retain) UITextField *PillBayNo;
- (IBAction)buttonClicked:(id)sender;
#end
and
ConsumePillServiceViewController.m as follows
#import "ConsumePillServiceViewController.h"
#implementation ConsumePillServiceViewController
#synthesize Me_id;
#synthesize Mem_device_id;
#synthesize Test_datetime;
#synthesize Creation_id;
#synthesize PillBayNo;
- (IBAction)buttonClicked:(id)sender {
NSString *soapMsg =
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<PickPill xml1ns=\"http://tempuri.org/\">";
NSString *smMe_id=
[soapMsg stringByAppendingString:
[NSString stringWithFormat:
#"<Me_id>%#</Me_id>",Me_id.text]];
NSString *smMem_device_id=
[smMe_id stringByAppendingString:
[NSString stringWithFormat:
#"<Mem_device_id>%#</Mem_device_id>",Mem_device_id.text]];
NSString *smTest_datetime=
[smMem_device_id stringByAppendingString:
[NSString stringWithFormat:
#"<Test_datetime>%#</Test_datetime>",Test_datetime.text]];
NSString *smCreation_id=
[smTest_datetime stringByAppendingString:
[NSString stringWithFormat:
#"<Creation_id>%#</Creation_id>",Creation_id.text]];
NSString *smPillBayNo=
[smCreation_id stringByAppendingString:
[NSString stringWithFormat:
#"<PillBayNo>%#</PillBayNo>",PillBayNo.text]];
NSString *smRestMsg=
[smPillBayNo stringByAppendingString:
#"</PickPill>"
"</soap:Body>" "</soap:Envelope>"];
soapMsg=smRestMsg;
//---print it to the Debugger Console for verification---
NSLog(soapMsg);
NSURL *url = [NSURL URLWithString: //create a URL load request object using instances :
#"http://72.44.151.178/PickPillService.asmx"];//of the NSMutableURLRequest and NSURL objects
NSMutableURLRequest *req =
[NSMutableURLRequest requestWithURL:url];
//opulate the request object with the various headers, such as Content-Type, SOAPAction, and Content-Length.
//You also set the HTTP method and HTTP body
NSString *msgLength =
[NSString stringWithFormat:#"%d", [soapMsg length]];
[req addValue:#"text/xml; charset=utf-8"
forHTTPHeaderField:#"Content-Type"];
[req addValue:#"http://tempuri.org/PickPill"
forHTTPHeaderField:#"SOAPAction"];
[req addValue:msgLength
forHTTPHeaderField:#"Content-Length"];
//---set the HTTP method and body---
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self]; //establish the connection with the web service,
if (conn) { //you use the NSURLConnection class together with the request object just created
webData = [[NSMutableData data] retain];//webData object use to receive incoming data from the web service
}
}//End of button clicked event
-(void) connection:(NSURLConnection *) connection //Recive response
didReceiveResponse:(NSURLResponse *) response {
[webData setLength: 0];
}
-(void) connection:(NSURLConnection *) connection //Repeative call method and append data to webData
didReceiveData:(NSData *) data {
[webData appendData:data];
}
-(void) connection:(NSURLConnection *) connection//If error occure error should be displayed
didFailWithError:(NSError *) error {
[webData release];
[connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc]
initWithBytes: [webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
//---shows the XML---
NSLog(theXML);
[connection release];
[webData release];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[Me_id release];
[Creation_id release];
[Mem_device_id release];
[Test_datetime release];
[PillBayNo release];
[soapResults release];
[super dealloc];
}
#end
I did all things as shown in the website and when i built application it successfully built
but in the debuggin window i see
(gdb) continue
2010-03-17 09:09:54.595 ConsumePillService[6546:20b] <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><PickPill xml1ns="http://tempuri.org/"><Me_id>A00000004303</Me_id><Mem_device_id>1011</Mem_device_id><Test_datetime>03/13/2010 07:34:38</Test_datetime><Creation_id>Hboxdata</Creation_id><PillBayNo>2</PillBayNo></PickPill></soap:Body></soap:Envelope>
(gdb) continue
(gdb) continue
(gdb) continue
2010-03-17 09:10:05.411 ConsumePillService[6546:20b] DONE. Received Bytes: 476
2010-03-17 09:10:05.412 ConsumePillService[6546:20b] <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>Server was unable to process request. ---> One or more errors occurred during processing of command.
ORA-00936: missing expression</faultstring><detail /></soap:Fault></soap:Body></soap:Envelope>
It should return me true if all things are ok
What is this ORA-00936 error all about
as it is not releted with webservice
Please help me solving this problem
Thanks in advance,
Vaibhav Deshpande