iPhone Programming Tutorial – Intro to SOAP Web Services

  • Twitter
  • Facebook
  • Digg
  • Reddit
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
November 3rd, 2008 Posted by: (ELC) - posted under:Tutorials

This tutorial was contributed by Dave (AKA Clarke76) on the Forums.

WebSite: http://viium.com

-Main project on site is eDuo. A .Net app that connects to OWA Exchange and forwards to IMAP account. Free program for those who can’t use Active Sync

 
Important Links:

[WebService] http://viium.com/WebService/HelloWorld.asmx

http://developer.apple.com/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html

http://developer.apple.com/documentation/Cocoa/Conceptual/XMLParsing/XMLParsing.html

http://www.w3schools.com/soap/default.asp

-After creating our XML data / SOAP  request, we create a URLRequest. We add HTTP Header values, those values you read from the WebService.

-We set the HTTP Method to POST

-We set out HTTP Body to the xml file we created

-We then create our connection, using the request we just setup.

 

 

-Once the connection is setup and delegate is set to self, we need to setup out connection delegate methods.

-The first method just makes sure it can make a connection. If it can, we make sure we have no data in our Data set so we clear it.

-Second method is called when re receive any data. If we do receive data, we just append it to our data set.

-Third Method handles any errors and releases our data and connection if an error occurs.

-Fourth Method: We take the data and create a string for Logging reasons, then release the string.

-We check to make sure an instance of xmlParser does not exist, if it does we release it.

-Create a new instance of xmlParser, set the delegate to self, want to resolve external entities, and start our parsing.

-release our connection and Data

 

 

Now we need to our our delegate methods for NSXMLParser

First method we are check the start of elements. If our element equals “HelloResult” we set our BOOL to true.  Second method records any data between an element if our BOOL is set to true.  Third method checks for our closing element. Once found sets our greeting, releases our MutableString, and set our BOOL back to false.

 

If you have any questions or comments, please leave them in the comments of this post.  You can download the sample code here.

  • Dan

    This is a great tutorial! I was looking for an intro into calling web services with the iPhone SDK, and this was a great starter.

    Keep up the great work on this site!!!!

  • iDeveloper

    Hi

    I was using something similar taking reference from http://kosmaczewski.net/2008/03/26/playing-with-http-libraries/

    But this method causes a problem when using on the device. It works fine on the simulator though. I’ve been trying to figure out the reason for sometime now.

    The problem with running it on the device is that the content length logged at the server is 0 if you send the SOAP envelope as the body of the request using POST. Any ideas why this would happen though?

  • http://paulodelgado.com Paulo

    lovely background image you got there :D

  • Mark

    Thanks for the tutorial. Just what I was looking for. Just one question (not about the tutorial), how do I setup custom code snippets? Cheers

  • http://quickiphonesolutions.blogspot.com sindhu tiwari

    Hi i have seen many tutorials on connecting a iphone application to a web Service this is one of the best , I want to know how to send parameters to a web service something like , There is a method which adds to given numbers and returns the result , those two numbers are the arguments of function now how to pass those parameters i will be thankful for the reply

    sindhu tiwari

  • http://www.madmaq,com maqish

    i believe NSXMLParser is not available on the device but usable on the simulator. that is why iDeveloper had some issues

  • zebrum

    How did you set up the text macros? Those look really handy.

  • lakshmikanthreddy

    hi ,

    awesome sample which u have put upon WebServices , but one small query , i am unable to run this sample can anyone guide me from the scratch for how to run this sample .

    thanks in advance.

  • http://qrios.de remei

    Thnx! This was really helpful for me.

  • Alice

    You can barely hear the audio at all… even at full
    volume.

    *PLEASE* speak into the mic.

  • Arash

    Thanks a lot for your great tutorial,
    I am writing an iphone application that will consume a .net webservice (basically it will get the list of radio channels with their url and an image)
    I wrote the ,net webservice and it is working fine but when I am trying to get the xml data in iphone I see that tags are
    not displayed correctly in debugger “” are shown like >< do you have any idea about this?

  • Steven

    Thanks for your tutorial ! just what i needed !

  • http://www.designsapling.com Jeremy White

    Even running the sample code, I get a warning in the method
    parser didStartElement:

    for the following line (line 100 in sample)
    recordResults = YES;

    Message is as follows:
    warning: assignment makes point from integer without a cast.

    Any ideas what this is about? Anyone else seeing this warning?

  • http://hugelawn.com Uffe Koch

    Good tutorial, well done.

    The warning is due to the superfluous * in the definition of recordResults, was:
    BOOL *recordResults;

    should be:
    BOOL recordResults;

  • http://www.designsapling.com Jeremy White

    Oh, i see! Thanks Uffe!

  • rubennm

    XML data / SOAP request??

  • rubennm

    How do we create the XML data / SOAP request

  • rubennm

    Forget it. Finished reading everything, saw some examples, created the needed soap messages at runtime. Thanks for a great tutorial

  • Pablo

    Hi! Great tutorial. By the way, i’ve been working on it and i wonder if you could answerme one question. Would it be posible to create a connection at the applicationWillTerminate method and wait for connectionDidFinishLoading to finish?

    Thank u!!

  • Rajiv

    Thanks for the useful tutorial…i have tried it. It works great with Web Services developed with Dot Net 2.0 framework. I have to consume webservice developed in Dot Net Framework 3.5, but its not getting any response from the server at the connectiondidfinish delegate method. The HttpConnection Status i m getting is 400 ( bad syntax ).
    The webservice is returning data from another web client.
    Can you please suggest me something to try.

  • james

    Thanks for the tutorial..

    how do we see the methods by writing ” @url “. what is the shortcut for it

  • Andreas

    I tried to receive data from a webservice which is almost the same as shown in the example. But I have an issue when coming to parsing the data from the response from the server.

    The response looks like this:

    string

    The issue in this case is that the string that is returned from the server is another XML file, where the format is not as it should be.
    The is >
    When trying to parse this string with the NSXMLParser function, I am not able to parse it as I want to due to the brackets. Looked for a solution for this, but only found something called “CFXMLCreateStringByUnescapingEntities”. But this give me another problem, something called CFStringRef. I do not know how I can use this function to get the XML format from the string, so it is possible to parse the data and present it in the application.

    As I understand the NSXMLParser needs a NSObject, not a string, and my question is then, how can I use the unescaping entities function and use it in the parser?

    Thanks in advance.

  • Andreas

    Saw that a lot of the text is missing in my previous post.
    But maybe it is shown in this:

    string

    The issue in this case is that the string that is returned from the
    server is another XML file, where the format is not as it should be.
    The is & gt;

  • John

    This was a great tutorial. Thanks for sharing it!

  • sindhu tiwari

    Hello Dude , Thanks for such a good blog .

    My aim is to consume a PHP driven webservice into my Iphone project .. can u provide some stuff on that .. i know that underlying architecture doesnt makes any difference but still for me I AM DUMB IN PHP .. headers and Soap Message will be enough for me ..

    Have a wonderful time ahead

    Thanks and Regards

    Sindhu Tiwari

  • JG

    How would you go about passing username/password if the XML Service was on a secure site that requires HTTPS and authentication?

  • Laurent

    Hi !
    Thanks for this tutorial.
    I’m new to iPhone and Apple programming (I come from .NET world) and I can’t believe it’s so complicated to consume web services in ObjectiveC… isn’t there a simpler way to do that ? With Visual Studio I can do that in 30 seconds.
    Thanks in advance for your answers.
    Laurent

  • my

    Hey,
    Tutorial is great. I just want to ask, how do you autocomplete the delegate methods?

  • http://ashwanik.blogspot.com Ashwani

    Hi
    Thanks for this articles

    I need one help in parsing XML

    Can any body tell me how to convert this XML into dictionary
    of the format
    key(son) value(NSArray of grandsons)

  • http://www.iphoneclub.nl/forum/f8/applicaties/f58/ontwikkelen-voor-de-iphone-sdk/25537-wsdl-iphone.html#post280034 WSDL .. iphone ? – iPhone Forum – alles over de Apple iPhone en iPhone 3G

    [...] SOAP is niet meer dan een http post geformateerd in XML dus je kunt het gewoon doen met NSURLConnection. Nadeel is natuurlijk dat je geformateerde XML zelf moet maken ipv dat je deze uitleest uit de WSDL. Hier heb je een tutorial die voor mij werkte: iCodeBlog Blog Archive iPhone Programming Tutorial – Intro to SOAP Web Services [...]

  • http://ashwanik.maqsoftware.com ashwani

    Hello :
    I used the code posted in this thread. It helped me a lot.
    But now I am facing an issue please help me.
    I want to send data to web service in the form of xml like

    <son>
    <child name=”XYZ”>
    </son>
    and get back some information related to child.
    But 0 byte response is received please help me in fixing this issue
    Thanks in advance

  • Sambha

    Excellent tutorial and blog. Its my favorite one now :) Thanks a ton for sharing your knowledge.

  • http://thecoleorton.com Cole

    hi there! this is a great tutorial!!

    question. what method can i use to return the value in the request below:

    string

    I see that NSLog(soapResults); returns what i want….but i’m not sure how to use it to catch if/when a request returns “false”, then i want to create a UIAlert telling the user their login failed. thanks!!

  • David

    Hi guys,

    I downloaded the source and tried to open the project file in xcode. I have the latest xcode running (only downloaded it around a month a go).

    I get a warning about this project having been saved under a “newer” version of xcode and when it opens the project there are three files that are colored red which it obviously cannot find:

    Foundation.framework
    Hello_SOAP.app
    UIkit.framework

    Any ideas?

  • David

    Sorry – disregard the last post – all works fine.

  • mu73

    Thank you very much for this tutorial. Great work.

  • http://itpblog.efuller.net/?p=737 ParaSite | Uploading

    [...] with the iPhone that I was at a total loss where to start. I began eyeing Dave’s tutorial on SOAP Web Services, but that just freaked me out a little too much. I needed something laid out simply first before I [...]

  • John

    Hello I am new to Iphone development and your tutorial helped me too much. Thanks for your this tutorial.

    Also please let me know how you get code sense window doe delegates for eg in video you typed “@url” and then delegate code window will appears how?

    Thanks in advance.

  • http://none NeedSomeAdvice

    Well i figured out how to read one value from an xml file from ur tutorial, but right now at the moment im doing a project that needs me to traverse through a tree of data and pick out certian keywords and display their values and since i learned ur way of retrieving xmldata i thought i come to you first.
    -thanks

  • Niketa

    I have used this example in my application. Its working properly on simulator. but not working on iphone device. Its giving “Connection error”. I have checked for wifi connection. its working properly.

  • for PHP guys to use the same feature

    If you are working on PHP and want to create a PHP server t respond to the SOAP requests, I have written a script, which uses NuSOAP library. You have to download it from sourceforge : http://sourceforge.net/projects/nusoap/files/

    In the obj-c code replace the soapmessage creation code with the following: Its easy to understand, sending the name inside name tags placed inside Hello tags.

    NSString *soapMessage = [NSString stringWithFormat:
    @"\n"
    "\n"
    "\n"
    ""
    "%@\n"
    "\n"
    "\n"
    "\n", nameInput.text
    ];

    Also replace the target URL with your php file URL:
    NSURL *url = [NSURL URLWithString:@"http://192.168.1.23/iPhone/index.php"];

    Now the PHP script is here. My server on Windows, I did it accordingly. Alter the NuSOAP include path as you placed on your computer.

    configureWSDL(‘Hello’, ‘urn:Hello’); //The 2nd param is the namespace & is optional

    /* register the method to expose */
    $server->register(
    ‘Hello’, // method name
    array(‘Hello’ => ‘xsd:string’), // input parameters
    array(‘HelloResult’ => ‘xsd:string’), // output parameters
    ‘urn:Hello’, // namespace
    ‘urn:Hello#Hello’, // soapaction
    ‘rpc’, // style
    ‘encoded’, // use
    ‘Says hello to the caller’ // documentation
    );

    /* Define the method as a PHP function */
    function Hello($name){
    return ‘hihihi… ‘ . $name; // return string inside HelleResult tag
    }

    /* Use the request to (try to) invoke the service */
    $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : ”;
    $server->service($HTTP_RAW_POST_DATA);

    exit();

    ?>

    hope it help somebody..

  • for PHP guys to use the same feature

    SORRY..!!!!!!

    all the strings are stripped off… :-(

  • AVG

    Hey Brandon/Dave,

    Thanks a lot for putting this tutorial up. Would it be possible to get a tutorial or a brief snippet of how to create and launch the web-service which you have used here.

    Thanks,

    AVG

  • Jwizzman

    what’s the deal with the .asmx file?
    how do I write it, let’s say I wanted to query a database, how would I so that?

  • http://www.multiflavours.com/?p=424 Web Services Tutorial

    [...] iCodeBlog » Blog Archive » iPhone Programming Tutorial – Intro to … [...]

  • http://www.naturhotel.it Christian Wohlgesinn

    Zu dem Thema gäbe es noch einiges zu schreiben.

  • http://urbasek.cz Jiri

    Hi,
    great tutorial for beginners, thanks for it.
    But whats realy awesome is code completion feature I have seen in the video. :)
    The author wrote ‘@url’ then pressed some keyboard shorcut and then got list of few delegate method definition to choose.
    I only know shortcut ESC (or ctrl + esc), but it is not working this way. Can author or anybody tell me, which shorcut is that?
    Also escaping xml string at beginning part of the video was also faster that I would expect, does anybody know how to do this magic things in XCode??
    Thanks much.

  • James

    Anyone got a php server that will work with this??

  • John

    Thanks for the example code. Easy to understand and modify! Got it working with a new web service in no time at all. Great Job!

  • Damien

    Hi, I’m trying to display a loading view while the web service is working, but I can’t succeed. I started with the source project we can download at the end of this article. Then, I added a simple LoadingView (UIView) with an UIActivityIndicatorView. I would like to display it just before calling the WS, then remove the loading view when the WS process is over. Any idea? Thank you for your help and this tutorial.

  • Khawar

    Video is not incomplete.

  • http://blog.alkimake.com/2009/09/json-rpc-bridge-to-xml-web-services-and-usage-in-objective-c-in-iphone/ JSON-RPC Bridge to XML Web Services and usage in Objective-C in iPhone | Alkim Gozen

    [...] the data on air, i totally got insane . If you want to know how bad is, try to visit these site : iPhone Programming Tutorial : Intro To Soap Web Services (or Turkish version : iPhone ile Web Service [...]

  • http://archanagella252@gmail.com archana g

    i am using .net2.0 webservices with same example given by you…but the connection was not established…

    could u please tell me any suggistions….

    thanks in advance…

  • http://gbif.org mgmbow

    Hello,
    I am downloading the code but I want the code of the file of php.

  • http://NA wanner

    It seems that the video isnt working? Is there something wrong on my end?

  • http://grabalife.com Kris

    I have created some wrapper classes and an objective C .NET dataset object class to easily incorporate passing datasets to your iphone app check it out!

    http://grabalife.com/2009/10/19/using-net-web-services-and-dataset-objects-in-your-iphone-app/

  • John

    I’ve tried to put this example in a class to do a login via web service. I get my user id and password from the NSUserDefaults. I build the SOAP envelope and get my validated userId back in the web service…that works!!!

    In the parser didEndElement method I have the value I want (userId) in soapResults and am setting it like this:

    myUserId = [[NSString alloc] initWithString:soapResults];

    I have this as a property in the class .h file as:

    @property(nonatomic, retain) NSString *myUserId;

    I’d like to be able access that value by my view controller class that creates the instance to use the web service as:

    LoginWebService *loginWebService = [[LoginWebService alloc] init];

    [loginWebService logUserIn];

    Right now it returns void and I try to get the value from the myUserId property. This does not work.

    I also tried returning a string from the logUserIn method where the SOAP message is defined…again no luck.

    I apologize if I’m missing something obvious…I’m coming from the .Net world and trying to pick this stuff up.

    Please provide some help or an example of wrapping your code into a class that can return a value as a result of the web service having been contacted, parsed and return a string to the instantiating class (in my case a userId). Any help would be appreciated, my head is a bloody stump from beating it against my Mac Book.

    Thanks in advance.

  • ashish

    my webservice is returning array and it shows #[] only if I am returning string from service it is shown properly. what needs to be done to get response array in client from server.

  • Shreedevi

    Hi John, Please could you provide the code, so access to access a login web service.
    I am having a login web service, but still i did not get how to pass paramters like username and password to the web service.and also how to capture the results in the application.
    Please help.. I am very new to iphone application development.

  • http://bjharringtoniii@hotmail.com Bobby

    Hello thank you for taking the time to
    create this tutorial it helped me alot.
    I am having one problem, getting an
    error when trying to access the webservice
    asmx file through the internet. When I try and
    access it via the internet I get an
    xml parsing error. When I right click
    the file and select view in browser it opens
    fine on the server. When I try and
    open the file on the server through
    port 8000 the port I am using for incoming
    internet connections I get the same error.
    What am I doing wrong?

  • aaron

    Nice tutorial. Thanks.

    John,

    Maybe I’m misreading your post, but I don’t see where you are making the value of “myUserID” externally visible. What does your “logUserIn” method look like? Are you synthesizing the getter/setter for “myUserID?”

  • Amit

    Gr8 Tutorial
    Thanks !!!!!!!

    It is working gr8 for .asmx service BUT not working while dealing with WSDL web service.
    I am getting following error …

    Error Code: 407 Proxy Authentication Required. The ISA Server requires authorization to fulfill the request. Access to the Web Proxy filter is denied. (12209)

    Plz Help

  • http://sous-vetements.sexshop-soldes.com/ Khe

    Excellent blog, i like it. I should just give up and take lessons from you

  • Leo

    Thanks for the great tutorial.

    When i create my simple helloworld web service hosted by IIS on a local machine, my response from my IMAC is ZERO bytes, may I know what is the problem?

    Has it got to do with the hosting of the web service?
    I am able to see the operations page on Safari from the IMAC, hence connection should be fine.

    Thank you for any help.

  • Bhramar

    Gr8 Tutorial
    Thanks alot…

    Can i expect any clue or tutorial to connect database related Webservice which returns Datatable/Dataset.

    Thanks in Advance…

  • http://none Copyright issues

    I used ur code pretty much exactly in my project,just with some minor modifications, i just want to know if i have to put a copyright notice u might have made before i submit the application?

  • Aditya

    good tutorial…thanks!

  • Gendarme

    Great entry point into WS communication from iPhone! Works for WSDLs without any problems! Thanks a lot!

  • Heijtink

    Thank you for the great tutorial. I have one question though. In the example given you pass a string value ‘nameInput.Text’ to the NSString. However, how would one go about adding a boolean value to the NSString? I need to tell the Web Service whether I want the result back compressed or not. And I would like to set it to false.

  • http://www.idea.co.th/ Idea Digital

    Thank’s so much!

  • http://www.octagonpicnictables.com/ outside benches

    I lately came across your blog and have been reading along. I thought I would leave my first remark. I don’t know what to say except that I have loved reading. Respectable blog. I will keep visiting this blog very often.

  • http://www.soulcast.com/ipadnewssvcip/rss Hortensia Batterton

    Hey, Good evening it´s just i do totally dig Your blog, I wuold enjoy to blog a teaser on your incredible wordpress blog on my silly Apple iPad Website http://www.soulcast.com/ipadnewssvcip/rss would you grant me permission? XoX, Hortensia Batterton

  • Hitesh Savalia

    Really helpful to me.
    This is what I was looking for..

    Thanks a lot…
    Now I am trying to put data in the tableview..

  • Lee Mann

    Just wanted to thank you for this amazing video, it’s just suddenly made everything crystal clear! Thank you so much for sharing your knowledge.

  • John

    Hi All,
    This is a fantastic article. Thank you so much!

    I have a question: How would someone handle self signed or invalid SSL certificates in the context of this code?

    I’ve seen some people use;
    @implementation NSURLRequest(DataController)
    + (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
    {
    return YES; // Or whatever logic
    }
    @end

    which is dangerous. I was wondering if there’s a way to pop up a accept or decline before posting? Right now, this code simply refuses the connection.

    Thanks!

  • http://www.iphoneclub.nl/forum/f8/applicaties/f58/ontwikkelen-voor-de-iphone-sdk/58446-uitableview-soap.html#post443545 UITableview + SOAP – iPhone Forum – alles over de Apple iPhone, iPhone 3G en iPhone 3GS

    [...] te krijgen en dit weer te geven in een App. Hiervoor heb ik de volgende tutorial gebruikt: iPhone Programming Tutorial – Intro to SOAP Web Services | iCodeBlog en daar ergens wordt het opgeslagen vanuit een NSMutableString. Als ik hier NSMutableArray ofzo [...]

  • esko918

    OK im using this parser to grab my data from the net but how would i go about implementing a thread to call these functions, ive created a thread but after i call the first portion of the code and it creates the soap message it never goes past this function, How should i go about this cause i need to run my parsing in the background instead of on the main thread.

  • shishir mishra

    hi,thanks for this great tutrorial..

    i m just getting one prob

    Fatal error: Out of memory (allocated 524288) (tried to allocate 393216 bytes) in D:\xampp\htdocs\realify\start.php on line 1025

    and i dont know how to get rid of it.
    can u suggest something to resolve this one

    regards
    bobby

  • shishir mishra

    solved…..

  • lxLionHartxl

    Hi,

    Im having a little problem with the source code I downloaded from this site. This is the error message im seeing:

    : error: CFBundleIdentifier ‘com.yourcompany.Hello_SOAP’ contains illegal character ‘_’

    where do I find this CFBundleIdentifier?? And how do I solve this problem?

    Many thanks!

  • phongnt

    I need a project realy run online sour its rource code! thanks

  • phongnt

    I need a project realy run online sour its rource code of example get data from wsdl on iphone! thanks!

  • fixbug

    Hi Dan! can you send your code for me?

  • Angad Soni

    Hey, This is a great tutorial.. Thanks so much. I was wondering if your webservice site for this tutorial is working or because i don’t the result when i run the application.

  • http://www.permeative.com Abhilash

    Hi,

    Can any one help me how to write a soap request which returns the xml contains the data ?

    Regards,
    Abhilash

  • Dilip

    video needs Quick time player.

  • http://www.addonsolutions.com Mayur Shah

    Hi,

    Its really interesting information you have posted here I clear few doubts from this information thanks for sharing here

    Thanks

  • NeilB

    Excellent, thank you for putting this walkthrough together.

  • Tobias Becker

    Hi,

    this was exactly what we needed for our iPad app.

    Thanks a lot.

  • priyanka P S

    Hi john,

    I am new to iphone apps development..I also have an application to access a web service that is a login web service.I don’t know how to pass username and password as parameters…Can u plz mail me your code or can u give me an idea about to access alogin webservice..please help me..

    Thanks in advance

  • priyanka P S

    Hi,
    I am new to this iphone apps…can u help me to connect to a web service it has a login…I don’t know what to do ..please give me an idea…this example is also not working for me…what is the output look like in this example

  • Abhi

    My NSLog(theXML) result:

    <Menus>
    <Table1>
    <Restaurant_Name>CHICK-FIL-A</Restaurant_Name>
    <Restaurant_id>2748</Restaurant_id>
    <Phone>(404) 371-1466</Phone>
    <billing_city>DECATUR</billing_city>
    <billing_state>GA</billing_state>
    <billing_zip_code>30030</billing_zip_code>
    </Table1>
    </Menus>

    My final result is:

    CHICK-FIL-A
    2748
    (404) 371-1466
    DECATUR
    GA
    30030

    Now how I should read this result? Say, how should I display the value from above result..please help

  • Jon

    Don’t know if it’s just me but I can’t see the video.

  • kuldeepsidhu

    Thank you very much.
    it helped me a lot
    i need to send xml to sever and get response it is very easy with your tutorial…

    thanks again…

  • sam

    hi friend

    i want to create one form which will contain the colunm ” Name, address , Telephone no, Email and comments ”

    this will be entered by user in iphone app this information entered by the user should be saved in online server database
    i have to create this with webservice please i am new to this completetely i have to sub this with in 2 days please please help me

    Thanks
    Sam

  • Wang

    2

    2010-10-16 16:58:43.800 Hello_SOAP[1588:20b] ERROR with theConenction

    Is the server error?

  • Wang

    2010-10-16 17:06:34.028 Hello_SOAP[1674: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>
    <Hello xmlns=”http://viium.com/”>
    <name>2</name>
    </Hello>
    </soap:Body>
    </soap:Envelope>
    2010-10-16 17:06:35.692 Hello_SOAP[1674:20b] ERROR with theConenction

    Is the server error?

  • http://developerquestion.com/tutorial-about-web-service/ Tutorial about web service | DeveloperQuestion.com

    [...] 1 2 3 [...]

  • Ahmad kayyali

    How i can get the content length?

  • saleel

    Hi..
    Thanks for the gr8 tutorial…
    Now i have my xml data into an array and i want to put it in the table view. How can i do this?
    Please Help…
    Thanks in advance

  • saleel

    Hi..
    I also want to display this result in table view . How can i do this?
    please Help.
    Thanks

  • saleel

    Hi Hrishikesh
    I am getting xml responce from web service properly and also i can convert it into array but i am not able to display it in tableview can you plese help mi..

    Thanks.

  • richyaxe

    Thanks for great tutorial. I have 1 problem. i am using web service which is for addition of 2 numbers. when i enter two numbers in text fields 1 for each number & press add button it doesn’t show me result in text field of result. When i see in console , i am getting result in xml response. I cant display result in text field. plz help me thanks in advance.

    here is my web service logic =>
    [WebMethod]
    public int Addition(int a,int b)
    {
    return a + b;
    }

    Is it the case of convert string to int because you are using string ?

    Here is my code =>

    // header file

    #import

    @interface CalciWebServiceViewController : UIViewController {
    IBOutlet UITextField *number1;
    IBOutlet UITextField *number2;
    IBOutlet UITextField *result;
    NSMutableData *webData;
    NSMutableString *soapResults;
    NSXMLParser *xmlParser;
    BOOL *recordResults;
    }

    @property(nonatomic,retain) IBOutlet UITextField *number1;
    @property(nonatomic,retain) IBOutlet UITextField *number2;
    @property(nonatomic,retain) IBOutlet UITextField *result;
    @property(nonatomic,retain) NSMutableData *webData;
    @property(nonatomic,retain) NSMutableString *soapResults;
    @property(nonatomic,retain) NSXMLParser *xmlParser;

    -(IBAction)addButtonClick:(id)sender;

    @end

    // .m file

    //
    // CalciWebServiceViewController.m
    // CalciWebService
    //
    // Created by Mac Admin on 22/11/10.
    // Copyright __MyCompanyName__ 2010. All rights reserved.
    //

    #import “CalciWebServiceViewController.h”

    @implementation CalciWebServiceViewController

    @synthesize number1,number2,result,webData,soapResults,xmlParser;

    -(IBAction)addButtonClick:(id)sender
    {
    recordResults = FALSE;

    NSString *soapMessage = [NSString stringWithFormat:
    @"\n"
    "\n"
    "\n"
    "\n"
    "%@\n"
    "%@\n"
    "\n"
    "\n"
    "\n",number1.text,number2.text
    ];

    NSLog(soapMessage);

    NSURL *url = [NSURL URLWithString:@"http://" IP ADDRESS":1931/Service1.asmx"];

    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];

    NSString *msgLength = [NSString stringWithFormat:@"%d",[soapMessage length]];

    [theRequest addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [theRequest addValue:@"http://localhost/Addition" forHTTPHeaderField:@"SOAPAction"];
    [theRequest addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if(theConnection)
    {
    webData = [[NSMutableData data] retain];
    }

    else
    {
    NSLog(@”theConnection is NULL”);
    }

    [number1 resignFirstResponder];

    }

    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
    [webData setLength:0];
    }

    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
    [webData appendData:data];
    }

    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
    NSLog(@”ERROR with theConnection”);
    [connection release];
    [webData release];
    }

    -(void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
    NSLog(@”DONE,Received Bytes => %d”,[webData length]);
    NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length: [webData length] encoding:NSUTF8StringEncoding];
    NSLog(theXML);
    [theXML release];

    if(xmlParser)
    {
    [xmlParser release];
    }

    xmlParser = [[NSXMLParser alloc] initWithData: webData];
    [xmlParser setDelegate:self];
    [xmlParser setShouldResolveExternalEntities: YES];
    [xmlParser parse];

    [connection release];
    [webData release];
    }

    -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName attributes: (NSDictionary *)attributeDict
    {
    if( [elementName isEqualToString:@"a"] || [elementName isEqualToString:@"b"])
    {
    if(!soapResults)
    {
    soapResults = [[NSMutableString alloc] init];
    }
    recordResults = TRUE;
    }
    }

    -(void)parser:(NSXMLParser *)parser foundCharacters: (NSString *)string
    {
    if( recordResults)
    {
    [soapResults appendString:string];
    }
    }

    -(void)parser:(NSXMLParser *)parser didEndElement: (NSString *) elementName namespaceURI: (NSString *)namespaceURI qualifiedNAme: (NSString *)qName
    {
    if( [elementName isEqualToString:@"a"] || [elementName isEqualToString:@"b"] )
    {
    recordResults = FALSE;
    result.text = soapResults;
    [soapResults release];
    soapResults = nil;
    }
    }
    /*
    // The designated initializer. Override to perform setup that is required before the view is loaded.
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
    // Custom initialization
    }
    return self;
    }
    */

    /*
    // Implement loadView to create a view hierarchy programmatically, without using a nib.
    - (void)loadView {
    }
    */

    /*
    // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
    - (void)viewDidLoad {
    [super viewDidLoad];
    }
    */

    /*
    // Override to allow orientations other than the default portrait orientation.
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    }
    */

    - (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 {
    [xmlParser release];
    [super dealloc];
    }

    @end

    // Console Output

    [Session started at 2010-11-24 08:12:34 -0500.]
    2010-11-24 08:13:19.436 CalciWebService[929:20b]

    1
    1

    2010-11-24 08:13:21.683 CalciWebService[929:20b] DONE,Received Bytes => 343
    2010-11-24 08:13:21.720 CalciWebService[929:20b]

    2

    Terminating in response to SpringBoard’s termination.

  • richyaxe

    I dont know why my xml contents are not displayed in my above comment . In console output,
    1 & 1 are the inputs and i am geeting 2 as output.

  • Mahendra Raut


    -(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);
    [theXML release];

    if (xmlParser)
    {
    [xmlParser release];
    }
    xmlParser = [[NSXMLParser alloc] initWithData: webData];
    [xmlParser setDelegate: self];
    [xmlParser setShouldResolveExternalEntities:YES];
    [xmlParser parse];

    [connection release];
    [webData release];
    }

    //---when the start of an element is found---
    -(void) parser:(NSXMLParser *) parser
    didStartElement:(NSString *) elementName
    namespaceURI:(NSString *) namespaceURI
    qualifiedName:(NSString *) qName
    attributes:(NSDictionary *) attributeDict {

    if( [elementName isEqualToString:@"AddResult"])
    {
    if (!soapResults)
    {
    soapResults = [[NSMutableString alloc] init];
    }
    elementFound = YES;
    }
    }

    -(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string
    {
    if (elementFound)
    {
    [soapResults appendString: string];
    }
    }

    //---when the end of element is found---
    -(void)parser:(NSXMLParser *)parser
    didEndElement:(NSString *)elementName
    namespaceURI:(NSString *)namespaceURI
    qualifiedName:(NSString *)qName
    {
    if ([elementName isEqualToString:@"AddResult"])
    {
    //---displays the Result---
    NSLog(soapResults);
    UIAlertView *alert = [[UIAlertView alloc]
    initWithTitle:@"Result is"

    message:soapResults
    delegate:self
    cancelButtonTitle:@"OK"
    otherButtonTitles:nil];
    [alert show];
    [alert release];
    [soapResults setString:@""];

    }
    }

  • Mahendra Raut

    @richyaxe : try above solution.

  • richyaxe

    thanks for reply…
    i will try it

  • saleel

    HI Mahendra
    can you please tell mi how to display the parsed xml into UITableView insted of alertView.

    Thanks

  • Prasad

    Can anyone upload the above soaptutorial.mov video by Dave on youtube or anywhere as the above video is not working on Safari, Chrome, Firefox. I don’t know if something is wrong with the video or at my end.

    I need that video .. please help

    Thanks in advance

  • mike

    hi
    does someone know what is the shortcut keys to bring delegate function out after we type”@url” in editor? Brandontreb uses that a lot times in the tutorial video.
    thanks !!!!! I hope someone can tell me that trick. thanks for help

  • http://www.cygnismedia.com/ Create iPhone App

    from this post i got 20% of m solution thanks for share :)

  • http://www.worldoftrade.com/ Rolex Parts

    Wowo !!
    This i phone application is very informative and useful.
    i like this post

  • http://www.ensisinfo.com MaheshBabu

    I am fallow the same procedure but my received data is 0
    my code is

    NSString *soapMsg =
    [NSString stringWithFormat:
    @""
    ""
    ""
    ""
    "MortgageGetLoanOfficerInfo"
    "919703661366"
    ""
    ""
    ""
    ];
    NSLog(@”%@”,soapMsg);
    NSURL *url = [NSURL URLWithString:@"http://10.10.8.7/MobileGenericWebservice/GenericWebService.asmx"];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]];
    [req addValue:@"text/xml; charset=utf-8"
    forHTTPHeaderField:@"Content-Type"];
    [req addValue:@"Mortgage/GenericAndroidMethod"forHTTPHeaderField:@"SOAPAction"];
    [req addValue:msgLength
    forHTTPHeaderField:@"Content-Length"];
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];

    conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    if (conn) {
    NSLog(@”connected %@”,conn);
    webData = [[NSMutableData data] retain];
    }
    }

    -(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
    NSLog(@”connect %@”,connection);
    [webData setLength: 0];
    }

    -(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
    NSLog(@”test %@”,data);
    [webData appendData:data];
    }
    -(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
    NSLog(@”error will occer %@”,error);
    [webData release];
    [connection release];
    }
    -(void) connectionDidFinishLoading:(NSURLConnection *) connection {
    NSLog(@”DONE. Received Bytes: %d”, [webData length]);
    NSLog(@”recived data %@”,webData);
    NSString *theXML = [[NSString alloc]
    initWithBytes: [webData mutableBytes]
    length:[webData length]
    encoding:NSUTF8StringEncoding];
    //—shows the XML—
    NSLog(@”%@”,theXML);
    [theXML release];

    [connection release];
    [webData release];
    }

    whats wrong can any one pls help

  • http://www.ensisinfo.com MaheshBabu

    i did n’t receive data, here is my code. whats the wrong
    -(IBAction)buttonClick:(id)sender
    {

    NSString *soapMessage = [NSString stringWithFormat:
    @"\n"
    "\n"
    "\n"
    "\n"
    "GenericAndroidMethod\n"
    "919703661366
    \n"
    "\n"
    "\n"
    "\n"
    ];
    NSLog(@”xml input %@”,soapMessage);

    NSURL *url = [NSURL URLWithString:@"http://10.10.8.7/MobileGenericWebservice/GenericWebService.asmx"];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];

    [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [theRequest addValue: @"Mortgage/GenericAndroidMethod" forHTTPHeaderField:@"SOAPAction"];
    [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if( theConnection )
    {
    webData = [[NSMutableData data] retain];
    }
    else
    {
    NSLog(@”theConnection is NULL”);
    }

    [nameInput resignFirstResponder];

    }

    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    if ([response respondsToSelector:@selector(allHeaderFields)]) {
    NSDictionary *dictionary = [httpResponse allHeaderFields];
    NSLog([dictionary description]);
    }
    NSLog(@”111111111111Recived response %@”,response);
    [webData setLength: 0];
    }
    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
    NSLog(@”2222222222Recived data %@”,data);
    [webData appendData:data];
    }
    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
    NSLog(@”3333333333ERROR with theConenction”);
    [connection release];
    [webData release];
    }
    -(void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
    NSLog(@”4444444444DONE. Received Bytes: %d”, [webData length]);
    NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
    NSLog(@”5555555555555Recived data %@”,theXML);
    [theXML release];

    if( xmlParser )
    {
    [xmlParser release];
    }

    xmlParser = [[NSXMLParser alloc] initWithData: webData];
    [xmlParser setDelegate: self];
    [xmlParser setShouldResolveExternalEntities: YES];
    [xmlParser parse];

    [connection release];
    [webData release];
    }

    -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
    attributes: (NSDictionary *)attributeDict
    {
    if( [elementName isEqualToString:@"HelloResult"])
    {
    if(!soapResults)
    {
    soapResults = [[NSMutableString alloc] init];
    }
    recordResults = TRUE;
    }
    }
    -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
    {
    if( recordResults )
    {
    [soapResults appendString: string];
    }
    }
    -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
    {
    if( [elementName isEqualToString:@"HelloResult"])
    {
    recordResults = FALSE;

    [soapResults release];
    soapResults = nil;
    }
    }

  • Roy Glunt

    This is a good article. But do you have an example of calling a WCF server that requires username and password authentication. I am in the process of a project and I need to be able to call a WCF service (that requres username/password ) from the iPhone/iPad. The result coming back will be an array of objects.

  • http://www.worldoftrade.com/ Ring Jewelry

    Excellent tips and a great article. Nicely done!
    wow that’s great

    Your post have good information photo are also inspire to me on this website…….
    thanks for sharing great information…

  • Pete

    Thanks for the great tutorial

  • Joe

    Just wanted to say thanks so much for making this tutorial. I’ve tried various code-generation utilities, and scoured the web for information on iPhone and SOAP. Way too many hours. With your tutorial, I was actually able to get it working. Much appreciated!

  • Joe

    This was a challenge for me too. I was able to tackle it by implementing
    - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

  • http://www.carteenee.com/ รถยนต์มือสอง

    I’d have to give blessing with you on this. Which is not something I typically do! I love reading a post that will make people think. Also, thanks for allowing me to comment!

  • Eman Hosny

    Hi,

    I am trying to retrieve a file using soap envelope as mentioned but the problem is that when i parse the xml and find on the element to read the file , the data is encoded as UTF-8 and i want to get it as a binary inorder to be able to save the file ..

    My problem is that i cann’t get the binary data from the xml …

  • khushi

    HI
    Im new in iphone world. so plz can u give me idea, how to receive data for parsing? Actually i m sending data by NSURLConeection , but i have no idea how can receive data for parsing?

    Thanxxxxxxxxx

  • Alish

    The video is not available!
    http://icodeblog.com/wp-content/uploads/2008/11/SOAPTutorial.mov

    Is it possible to let me where can I find it!

  • Siddam1986

    if its string we can handle it but if the call to xml web service returns byte[] then how will you parse it.
    Show me sample code for it. I need to display the byte[] in iphone

  • sahil

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict

  • Sarokhatch

    can someone recommend a book on web services. I am new to web services but I am NOT new to iphone development.
    Thanks

  • Sarokhatch

    can someone recommend a book on web services. I am new to web services but I am NOT new to iphone development.
    Thanks

  • emrickenoch

    It’s not scripted. It isn’t a monologue. Mobile advertising and apps
    have added to the new, online conversation you have to start with
    consumers.  iphone app developers
    ipad application design

  • Pedro

    http://sudzc.com/

    just put your wsdl and generate…

  • Alexsmayfield

    This is helpful to the extent of me understanding what your doing and being able to do it with what I’m wanting to do.
    I’m getting quite confused as of where I’m needing to put what I need where?
    If you can help put this example into the blondest of blonde terms would be much appreciated. 

  • Alexsmayfield

    oh nevermind I got it!

  • Stickytroll

    Have you deliberately put the code in images so that no-one can copy and paste it?

  • Daney

    the sample code link is available.. just after the post ends. Pretty small link though, could easily be missed.

  • Oudy1st

    i will try

  • Husain

    How do I consume web service in objective -C using secured protocol like HTTPS?

  • iremk

    great tutorial about soap services! finally done what i needed to and without pain. although it took a lot to find this page !

  • Bizzareshishir

    This is a great tutorial , but I am always getting this : 

    2011-10-18 20:18:30.134 Hello_SOAP[2833:207] ERROR with theConenction

  • ekrem aksoy

    hello,i would like to run this code but i didnt receive any output just it say buil successfuly and when i press button nothing appear.. how can i fix it pls helpp??

  • ekrem aksoy

    hello,i would like to run this code but i didnt receive any output just it say buil successfuly and when i press button nothing appear.. how can i fix it pls helpp??

  • Randeep Singh

    Nice Tutorial, but its web service is not working now. Please do something in this respect.

  • Gangeshvar

    This is helpful to the extent of me understanding what your doing and being able to do it with what I’m wanting to do.
    I’m getting quite confused as of where I’m needing to put what I need where?
    If you can help put this example into the blondest of blonde terms would be much appreciated.
    GP…

blog comments powered by Disqus