I wanted to call SOAP services, saw many document's over link.
I used one of those like the BestSoaptool from github https://github.com/yillars/BestSoapToolwithafnet, but I am still lacking some where and not able to get the response.
I am using the link as -- "https://aaa.com/Customers.svc?singleWsdl" and then the method name "xxx" but I don't get a response.
If not this can any one give me some better idea as to how should I implement this?
Thanks.
I've added sample SOAP implementation in iOS in my wordpress blog. Hope this will help you https://wordpress.com/post/bharathreddys.wordpress.com/6
Lets assume the following .wsdl url is the source URL.
http://www.webservicex.net/geoipservice.asmx?WSDL
Create a SOAP Envelop and SOAP Header.
NSMutableString * soapHeader = #"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\""
" xmlns:hom=\"http://www.webservicex.net/">"
"<soapenv:Header/>";
Be remember that "xmlns:hom", text next to ":" is the word which will be used as the targetnamespace reference for the service call which will be added in SOAP body.
SOAP body will be as follows :
[soapHeader appendString:#"<soapenv:Body>"];
[soapHeader appendString:#"<hom:GetGeoIP>"]; // add the body parameters
[soapHeader appendString:#"<hom:IPAddress>0.0.0.1</hom:IPAddress>"];
[soapHeader appendString:#"</hom:GetGeoIP>"];
[soapHeader appendString:#"</soapenv:Body>"];
[soapHeader appendString:#"</soapenv:envelope>"];
Now the web service is as follows:
NSMutableString * requestStr = [NSMutableStringstring];
[requestStr appendString:soapHeader];
NSString * urlStr = #"http://www.webservicex.net/geoipservice.asmx?WSDL";
NSURL * url = [NSURL URLWithString:urlStr];
NSMutableURLRequest * request = [[NSMutableURLRequestalloc] initWithURL:url];
[request setValue:#"http://www.webservicex.net/GetGeoIP" forHTTPHeaderField:#"SOAPAction"];
[request setValue:#"http://www.webservicex.net/" forHTTPHeaderField:#"targetNamespace"];
[request setValue:#"text/xml;charset=UTF-8"forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:requestBody];
[request setHTTPMethod:#"POST"];
[request setValue:[NSStringstringWithFormat:#"%d",[requestBody length]] forHTTPHeaderField:#"Content-Length"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
BOOL isSuccess = YES;
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(#"received data---%#",response);
if(connectionError != nil) {
isSuccess = NO;
NSLog(#"connection error with code %d",connectionError.code);
}
NSDictionary * responseDictionary = [NSDictionary dictionary];
if([httpResponse statusCode] == 200) {
isSuccess = YES;
//Do something with the received dictionary.
}];
This is the basic platform how we can make a simple SOAP based web service calls in iOS.
Happy coding !!!!
Related
I am trying to set up an iOS client to use SignalR-ObjC with our web service. When we use the long polling approach, everything seems to work but it has issues of its own with our production environment. So I have been instructed to switch to using the Web Sockets approach. Based on code examples I've seen online I think it should be working with what I have but the service is returning an error through the webSocket:didFailWithError: method. Here's the error:
Error Domain=org.lolrus.SocketRocket Code=2132 "received bad response code from server 403" UserInfo={NSLocalizedDescription=received bad response code from server 403}
Here's my code for setting up the connection, found in our AppDelegate file:
<!-- language:objective c -->
-(void)initializePushNotificationsConnection
{
// Connect to the hub on the service
SRHubConnection* localHubConnection = [SRHubConnection connectionWithURL:kSignalRServiceUrl];
SRHubProxy* notifications = (SRHubProxy*)[localHubConnection createHubProxy:#"notificationHub"];
[notifications on:#"notificationSent" perform:self selector:#selector(addMessage:)];
localHubConnection.started = ^{
NSString* userGuid = [OURAppSettings sharedSettings].loginModel.theUser.userGuid;
if (!userGuid)
userGuid = #"";
NSString* connId = self.hubConnection.connectionId;
if (!connId)
connId = #"";
NSDictionary* connectionDict = #{#"UserGuid": userGuid, #"Model": connId};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:connectionDict options:0 error:nil];
NSURL* connectionRegistrationServiceUrl = [NSURL URLWithString:kSignalRConnectionRegistrationUrl];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:connectionRegistrationServiceUrl];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse* response, NSData* data, NSError* connectionError)
{
if (connectionError)
{
NSLog(#"Error: %#", connectionError);
return;
}
}];
return;
};
//Set the object to the local property to break the strong connection so the block can reference the object
self.hubConnection = localHubConnection;
SRWebSocketTransport *webSocket = [[SRWebSocketTransport alloc] init];
[self.hubConnection start:webSocket];
}
I've tried multiple suggestions from Github and SO but none of them are solving this issue. I suspect there is a problem with how the web service is setup but I'm not an IIS expert nor do I have easy access to the setup. I'm basically just guessing at solutions at this point, so if anyone has any thoughts or suggestions at all I'm open to hearing them.
Is there any resource efficient way (something that does not tie up the main thread) in IOS to check the existence of a remote file?
I have user images stored on a server. While there is a consistent url scheme, some images are .jpg, others are .gif, etc. so to get the correct image name, I need to check does user/file.gif exist, user/file.jpg exist etc. in order to download the file to the IOS app.
I found this code in another answer in IOS
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"HEAD"];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
But I am not sure how to use it. Ideally, I would like to get a boolean yes or no as to whether the .gif file exists, the .jpg file exists etc for the users profile pic so I can fill in the correct name to download the user pic.
The alternative would be to write a service on the back end to return the file but wondering if it can all be done in IOS.
Thanks for any suggestions.
**Use this function below to check whether file exists at specified url**
+(void)checkWhetherFileExistsIn:(NSURL *)fileUrl Completion:(void (^)(BOOL success, NSString *fileSize ))completion
{
//MAKING A HEAD REQUEST
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fileUrl];
request.HTTPMethod = #"HEAD";
request.timeoutInterval = 3;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
if (connectionError == nil) {
if ((long)[httpResponse statusCode] == 200)
{
//FILE EXISTS
NSDictionary *dic = httpResponse.allHeaderFields;
NSLog(#"Response 1 %#",[dic valueForKey:#"Content-Length"]);
completion(TRUE,[dic valueForKey:#"Content-Length"]);
}
else
{
//FILE DOESNT EXIST
NSLog(#"Response 2");
completion(FALSE,#"");
}
}
else
{
NSLog(#"Response 3");
completion(FALSE,#"");
}
}];
}
I want calling method webService by parameter Json from IOS, but I received an error.
Code Server Side (WCF):
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/test/{input}")]
int test(string input);
I want get input (parameter method and url) = typeof (Json)
Code Client Side (iOS-objective C) :
NSString *json = [self convertToJson:myObject];
NSString *urlComplete = [NSString stringWithFormat:#"%#%#",#"http://test.com/Service.svc/test/",json];
urlComplete = [urlComplete stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:urlComplete]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:
^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (data.length > 0 && connectionError == nil) {
NSString *string = [[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"Data Recived:\n %#",string);
}
else{
NSLog(#"Error %#",[connectionError description]);
}
}];
The webService is being tested by windowsPhone and returns OK but doesn't work with iOS.
Please help me!
thanks:)
Error description "HTTP Error 400. The request URL is invalid." clears that url you are passing is incorrect. Please cross check with windows team if they are appending the JSON to the get URL.
Generally, if you want to post data you can set the requestdata which is JSON and go for either a PUT or POST request instead of GET request.
I currently have a screen with 2 tables. I'm getting the data synchronously and putting it on the screen. Code looks something like:
viewController.m
DBAccess_Error_T = [getList:a byCompanyID:1];
DBAccess_Error_T = [getList:b byCompanyID:2];
[self putListAOnScreen];
[self putListBOnScreen];
DBAccess.m
+ (DBAccess_Error_T)getList:(NSMutableArray*)a byCompanyID:(NSInteger)cID
{
// Pack this up in JSON form
[self queryDB:postData];
// Unpack and put it into variable a
}
+ (id)queryDB:(id)post
{
// Send request
// Get back data
}
I'm now trying to switch this over to async and I'm struggling. It's been hard even with website tutorials and documentations.
Since all of my database utilities are in separate files from the viewControllers, I'm not sure how I can use the didReceiveData and didReceiveResponse handlers. Also, since I have 2 arrays to fill for my 2 tables, how do I distinguish the difference in didReceiveData?
Instead, what I'm trying to do now is use sendAsynchronousRequest, but it seems I need to create an unpack function for every send function...let me know if I'm way off here...it looks something like:
viewController.m stays the same
DBAccess.m
+ (DBAccess_Error_T)getList:(NSMutableArray*)a byCompanyID:(NSInteger)cID
{
NSDictionary *post = /*blah blah*/
[self queryDB:post output:(a)];
}
+ (id)queryDB:(id)post output:(id)output
{
NSError *error;
NSData *jsonPayload = [NSJSONSerialization dataWithJSONObject:post options:NSJSONWritingPrettyPrinted error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:jsonPayload];
[NSURLConnection sendAsynchronousRequest:request
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error)
{
if ([data length] >0 && error == nil)
{
[self unpackDataForList:output data:data]; // This function needs to be different depending on which function called queryDB...the data will be unpacked in a different way
}
}
}
+ (void)unpackDataForList:(id)output data:(NSData*)data
{
// Do my unpacking here and stick it into 'output'.
}
How can I call a different unpackData function? are function pointers the right way to do this? Is this approach way off? Any tips would be greatly appreciated!
Have you ever looked at ASIHTTPRequest? It makes your life a lot easier by allowing you to use blocks. Here's an example of how to make an asynchronous request:
- (IBAction)grabURLInBackground:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://allseeing-i.com"];
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
// Use when fetching text data
NSString *responseString = [request responseString];
// Use when fetching binary data
NSData *responseData = [request responseData];
}];
[request setFailedBlock:^{
NSError *error = [request error];
}];
[request startAsynchronous];
}
You can find more information here:
http://allseeing-i.com/ASIHTTPRequest/
I am trying to figure out how to send data to the server but currently without any progress.
What I know
On the server I have got some php script that return me data in response
for example with this URL: http://test.com/mobile_api/register
this script get next parameters:
id
name
info
time
so the string which I need looking like below
http://test.com/mobile_api/register?id=1000&name=alex&info=1.0&time=10000
What is best way to send this is string on the server
Now I'm trying to use ASIHTTPRequest. Can anybody send an example how to create correct request with my parameters.
This sample code should help you
-(void)sendRequest
{
int userId=10, time=10000;
NSString *name = #"ABC";
float info = 1.0;
NSString *urlString = [NSString stringWithFormat:#"http://test.com/mobile_api/register?id=%d&name=%#&info=%f&time=%d",userId,name,info,time];
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
//You need to add ASIHTTPRequestDelegate in header(.h) file
[request setDelegate:self];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
// Use when fetching binary data
NSData *responseData = [request responseData];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}