Calling Webservice in iPhone application? - objective-c

I am using soap webservice.
In that i am calling one webmethod. Here if i call from one part of my code is working fine and calling service successfully and retriving data successfully.
But if i calling same method from another part of code of same class is not responding and not getting any data from service. Why is going like that can any one help me please.
Thanks in advance
In detail.m
-(void) downloadAndParse:(NSMutableURLRequest *)sentReq {
conn = [[NSURLConnection alloc] initWithRequest:sentReq delegate:self];
if (conn) {
webData = [[NSMutableData data] retain];
}
}
-(void)fullBarcodeSearch:(NSString *)code {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
URLRequest *r = [[URLRequest alloc] init];
NSMutableURLRequest *req = [r fullBarcodeSearch:code];
[r release];
[self downloadAndParse:req];
}
In URLRequest.m
-(NSMutableURLRequest *) addHeaderToSoapXML:(NSString *) soapMsg {
NSURL *url = [NSURL URLWithString:str];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d",[soapMsg length]];
[req addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"content-type"];
[req addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody:[soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
return req;
}
if service not called then i am getting error like this
*oid _WebThreadLockFromAnyThread(bool), 0x6958130: Obtaining the web lock from a thread other than the main thread or the web thread. UIKit should not be called from a secondary thread.*
Please any one help me
Thanks in advance

You need an NSURLConnection to execute the NSURLRequest. Lookup the Apple Docs on the class.
Something like:
[urlConnection sendSynchronousRequest:urlRequest returningResponse: &urlResponse error:&error]

Related

application is getting flashed while calling web services in iOS

i am using Soap web services to download the data from server. Device is getting flashed like flash light while downloading data. i am using synchrous request to get the data.
I could nt find out the reason why its getting flashed.
Please help me out, Thanks in advance.
Here is the code:
NSString *msgString = [[NSString alloc] initWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
"xmlns:xsd=\"http://http://www.w3.org/2001/XMLSchema\" "
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<GetCategories xmlns=\"http://tempuri.org/\"/>"
"</soap:Body>"
"</soap:Envelope>"];
NSURL *url = [NSURL URLWithString:[DefaultSettings getLink]];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
//---set the various headers---
NSString *msgLength = [NSString stringWithFormat:#"%d", [msgString length]];
[req addValue:#"text/xml" forHTTPHeaderField:#"Content-Type"];
[req addValue:#"http://tempuri.org/GetCategories" forHTTPHeaderField:#"SOAPAction"];
[req addValue:msgLength forHTTPHeaderField:#"Content-Length"];
//---set the HTTP method and body---
[req setHTTPMethod:#"POST"];
[req setHTTPBody:[msgString dataUsingEncoding:NSUTF8StringEncoding]];
NSError *error;
NSURLResponse *response;
NSData *webData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
xmlParser = [[NSXMLParser alloc] initWithData:webData];
[xmlParser setDelegate:self];
[xmlParser setShouldProcessNamespaces:NO];
[xmlParser setShouldReportNamespacePrefixes:NO];
[xmlParser setShouldResolveExternalEntities:YES];
[xmlParser parse];
after this, i am parsing the data. In the same method, i am calling 8 soap services one by one.
It's because you are using
[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];.
This method fires a synchronous connection and block the thread until you get a response from the server.
You can use wether
- (id)initWithRequest:(NSURLRequest *)request delegate:(id < NSURLConnectionDelegate >)delegate startImmediately:(BOOL)startImmediately
to start an asynchronous connection or start your previous method from another thread using NSThread
If your app is doing more than one request, you should create a RequestManager that will perform all the requests. This Manager will implements the NSURLConnectionDelegate. Then create your own protocol and implement it in your ViewController subclasses.
for instance, in your protocol you can add a method called
- (void)request:(int)requestID didFinishWithResult:(NSData *)data
the requestID is used to identify your request.
Call this method when any request finishes.

How to send Array of objects to JSON?

I am hitting a web service with array of objects. But in server side they are getting only null value for all the fields.
Client side code is:
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:urlRequest
delegate:self];
//************DATA formation
NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc]init];
NSMutableDictionary *jsonDict1 = [[NSMutableDictionary alloc]init];
[jsonDict setObject:#"3" forKey:#"rollNo"];
[jsonDict setObject:#"Ezhil" forKey:#"FirstName"];
[jsonDict setObject:#"Arasu" forKey:#"LastName"];
[jsonDict1 setObject:#"4" forKey:#"rollNo"];
[jsonDict1 setObject:#"XYZ" forKey:#"FirstName"];
[jsonDict1 setObject:#"ABC" forKey:#"LastName"];
NSArray *jsonArray=[[NSArray alloc]initWithObjects:jsonDict,jsonDict1, nil];
//Converting to JSON string.
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSString *jsonString = [writer stringWithObject:jsonArray];
NSLog(#"JSON String : %#",jsonString);
//************Setting DATA in URL
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[connection start];
// Code for response....
I dont know were i went wrong. Can any one help me for this issue.
Thanks in advance.
I'd scrap the SBJson stuff and just use the native controls...
Do everything the same as you are doing but remove the SBJsonWriter stuff and do this to set the body of the request...
[urlRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONWritingPrettyPrinted error:&error]];
That should work.
Thank you.. Application is working fine without any modification. The problem is with server side. But i think we can go with your suggestion instead of using external framework.
In both the case I am getting the json object like this,
JSON String :
[{"rollNo":"3","FirstName":"Ezhil","LastName":"Arasu"},
{"rollNo":"4","FirstName":"XYZ","LastName":"ABC"}]

IOS Application to send data to a Rest API service

I want to create an iPhone application to send data to a Rest API service. If the data is a string defined as geoX#35#geoY#65 which NSS method shall i use. Was thinking of NSString and NSMutablerequest to make my request and define my string but this isn't working atm.Also i am using NSURLconnection to establish a connection with the server(maybe that's faulty too). Anyone that can help ?
Thanks in advance.
Your connection data is using special characters and if you try to do this with GET method of NSURLConnection. It will Shows connection error. For this You have to use POST method like :
NSData *body = nil;
NSString *contentType = #"text/html; charset=utf-8";
NSURL *finalURL = #"YOUR URL WITH the ?input=";
NSString *yourString = #"geoX#35#geoY#65";
contentType = #"application/x-www-form-urlencoded; charset=utf-8";
body = [[NSString stringWithFormat:#"%#", yourString] dataUsingEncoding:NSUTF8StringEncoding];
if (nil==finalURL) {
finalURL = url;
}
NSMutableDictionary* headers = [[[NSMutableDictionary alloc] init] autorelease];
[headers setValue:contentType forKey:#"Content-Type"];
[headers setValue:mimeType forKey:#"Accept"];
[headers setValue:#"no-cache" forKey:#"Cache-Control"];
[headers setValue:#"no-cache" forKey:#"Pragma"];
[headers setValue:#"close" forKey:#"Connection"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:body];
self.conn = [NSURLConnection connectionWithRequest:request delegate:self];

Updating UI from callback function

I'm performing asynchronous request with ASI HTTP Request and I want to update Textbox with new information from the request, so I'm updating it from callback function.
Here is my code so far:
Second Class
- (void)Login {
NSLog(#"Login");
NSURL *url = [NSURL URLWithString:#"http://ts5.travian.sk/login.php"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDidFinishSelector:#selector(loginRequestFinished:)];
[request setDidFailSelector:#selector(loginRequestFailed:)];
[request startAsynchronous];
}
- (void)loginRequestFinished:(ASIHTTPRequest *)request
{
NSLog(#"Completed!");
NSString *response = [request responseString];
AppController *ac = [AppController getInstance];
[ac.textbox performSelectorOnMainThread:#selector(setStringValue:) withObject:response waitUntilDone:NO];
}
AppController is a main class. Setting text from there is working. But this code isnt doing anything. It just wrote 2 log lines to debug window.
Am I missing something?

NSURLConnection doesn't send data, but connects

The URL is written properly, I tested it in the browser with data and it sends properly, but when I make the request, it returns that it is successful, but it does not actually write the data. Any idea?
- (void)writeAboutMe:(NSString *)about withIcebreaker:(NSString *)icebreaker
{
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSString *urlString = [NSString stringWithFormat:#"http://nailorbail.net63.net/submit_about_and_icebreaker.php?username=%#&about=%#&icebreaker=%#",[SignInViewController getUsernameString] ,about,icebreaker];
NSLog(#"%#",urlString);
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
NSLog(#"Connection Successful");
else
NSLog(#"Connection could not be made");
[conn release];
}
It could be an encoding issue. What kinds of characters are in getUsernameString, about, and icebreaker? As Maudicus mentioned, you need to handle special characters in the URL yourself.
Try:
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
You have set up an asynchronous connection. Do you implement the NSURLConnection delegate protocol methods? Are any of them being called?
The creation of the connection instance doesn't say anything about it's success.
Check out some tutorials, like this one.