iOS mixed programming using SWIFT+OBJECTIVE-C call WebService

Source: Internet
Author: User
Tags soap xml parser

Recently, because of the needs of the project, to develop an iOS project using the Swift language, a simple requirement is to invoke the remote WebService data. The problem arises, there are many examples of using OC to call WebService on the Internet, but almost no example of using Swift to call WebService, I have been searching for several hours, is not satisfied with my request, how to do, the project will be ruined? Swift and OC, what should I choose?

Despair, fortunately swift and OC can perfectly implement mixed programming, which can be implemented with each other. And then on the Internet to find a use OC Access WebService example http://my.oschina.net/plumsoft/blog/75277, but also very grateful to the blogger. Well, let me write an example based on the swift and OC mixed programming call WebService. The bottom can download my source code OH.

(1) Create a new Swift project, and design the interface in Main.storyboard as follows, and bind the number input box and the query button to Viewcontrolle.swift respectively.


Note the following code is swift:

Import Uikitclass Viewcontroller:uiviewcontroller {    @IBOutlet weak var phonenumber:uitextfield!//enter the text box for the mobile phone number;        override func Viewdidload () {        super.viewdidload ()            }    override Func didreceivememorywarning () {        Super.didreceivememorywarning ()        //Dispose of any resources, can be recreated.    }    The response of the query button;    @IBAction func beginquery (sender:anyobject) {            }    }

(2) Right-click Project new files. Select Create a new Cocoa Touch Class, named Ocwebservice, and then pop up a bridging-header.h file and click Yes. Note: It is important to import the header file of this OC in the Bridging-header.h Bridge header file!!





(3) Then declare the following properties and methods in OCWebService.h, OCWebService.h specific code is as follows: Note that this code is OC.

#import <Foundation/Foundation.h> #import <uikit/uikit.h>//need two delegate, one for parsing XML and one for network connection ; @interface Ocwebservice:nsobject<nsxmlparserdelegate, nsurlconnectiondelegate> @property (Strong, Nonatomic) Nsmutabledata *webdata; @property (Strong, nonatomic) nsmutablestring *soapresults; @property (Strong, Nonatomic) Nsxmlparser *xmlparser; @property (nonatomic) BOOL elementfound; @property (Strong, nonatomic) NSString *matchingelement ; @property (Strong, Nonatomic) nsurlconnection *conn;-(void) query: (nsstring*) phonenumber;//Declare the Query method in the header file; @end

(4) The specific method in OCWEBSERVICE.M is implemented as follows: Note that this code is OC.

#import "OCWebService.h" @implementation ocwebservice@synthesize webdata; @synthesize soapresults; @synthesize Xmlparser; @synthesize elementfound; @synthesize matchingelement; @synthesize conn;-(void) query: (nsstring*) phonenumber{//Sets the keyword that we use to parse the XML later, corresponds to the getmobilecodeinforesult tag between the body tag in the response message Matchingelement = @ "Getmobilecodein    Foresult ";                         A SOAP message is created, and the content format is the principal entity part of the request message prompted on the Web site SOAP1.2 is used here; NSString *soapmsg = [NSString stringWithFormat:                         @ "<?xml version=\" 1.0\ "encoding=\" utf-8\ "?>" "<soap12:envelope" "Xmlns:xsi=\" http://www.w3.org/2001/xmlschema-instance\ "" "Xmlns:xsd=\" HTTP://WWW.W3.ORG/2                         001/xmlschema\ "" "Xmlns:soap12=\" http://www.w3.org/2003/05/soap-envelope\ ">"                         "<soap12:Body>" "<getmobilecodeinfo xmlns=\" http://webxml.com.cn/\ ">" "<mobilecode>%@</mObilecode> "" <userID>%@</userID> "" &LT;/GETMOBILECODEINFO&G t; ""        </soap12:Body> "</soap12:Envelope>", PhoneNumber, @ ""];    Print this XML string out NSLog (@ "%@", soapmsg); Create the URL, content is the second line of the previous request message packet host address plus the first line URL field nsurl *url = [Nsurl urlwithstring: @ "http://webservice.webxml.com.cn/    Webservices/mobilecodews.asmx "];    Create a request based on the URL above nsmutableurlrequest *req = [Nsmutableurlrequest Requestwithurl:url];    NSString *msglength = [NSString stringwithformat:@ "%lu", (unsigned long) [soapmsg length]]; Add the details of the request, corresponding to the fields in the first half of the request message [req addvalue:@ "application/soap+xml; charset=utf-8" forhttpheaderfield:@ "Content-type    "];    [Req addvalue:msglength forhttpheaderfield:@ "Content-length"];    Set the request line method to post, corresponding to the first line of the request message [req sethttpmethod:@ "POST"];    Add a SOAP message to the request [req sethttpbody: [soapmsg datausingencoding:nsutf8stringencoding]]; Create Connection conn = [[NsurLconnection alloc] Initwithrequest:req delegate:self];    IF (conn) {webdata = [nsmutabledata data]; }//called when the response was first accepted-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{[web Data setlength:0];} Append to WebData for each part of data received-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data {[WebData AppE Nddata:data];}    When an error occurs-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error {conn = nil; WebData = nil;} Call to complete receiving data (void) connectiondidfinishloading: (nsurlconnection *) connection {NSString *thexml = [[NSString alloc] In                                              Itwithbytes:[webdata Mutablebytes] Length:[webdata length]        Encoding:nsutf8stringencoding];    Print out the resulting XML NSLog (@ "%@", thexml);    Use Nsxmlparser to parse out the results we want xmlparser = [[Nsxmlparser alloc] initwithdata:webdata];    [Xmlparser setdelegate:self]; [XmlpaRser Setshouldresolveexternalentities:yes];    [Xmlparser parse]; } #pragma mark-#pragma mark XML Parser Delegate methods//begins parsing an element name-(void) Parser: (Nsxmlparser *) Parser didstartelement: ( NSString *) elementname NamespaceURI: (NSString *) NamespaceURI qualifiedname: (NSString *) QName attributes: (            Nsdictionary *) Attributedict {if ([elementname isequaltostring:matchingelement]) {if (!soapresults) {        Soapresults = [[Nsmutablestring alloc] init];    } elementfound = YES;  }}//appends the found element value, an element value may be appended several times-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *) string {if (Elementfound)    {[Soapresults appendstring:string]; }//End Parsing This element name-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI qualifiedname: (NSString *) QName {if ([elementname isequaltostring:matchingelement]) {UIAl                   Ertview *alert = [[Uialertview alloc] initwithtitle:@ "mobile phone number information"                                     Message:[nsstring stringwithformat:@ "%@", Soapresults]                                              Delegate:self cancelbuttontitle:@ "OK"        Otherbuttontitles:nil];        [Alert show];        Elementfound = FALSE;    Forced abort parsing [Xmlparser abortparsing];    }}//parsing the entire file ends-(void) Parserdidenddocument: (Nsxmlparser *) Parser {if (soapresults) {soapresults = nil;        }}//error, such as forced end resolution-(void) Parser: (Nsxmlparser *) parser parseerroroccurred: (Nserror *) parseerror {if (soapresults) {    Soapresults = nil; }} @end

(5) Finally come to Viewcontroller.swift's project master file using Swift to invoke the above method written in OC: The main implementation is in the Beginquery () method. Note that this is the SWIFT code

    The response of the query button;    @IBAction func beginquery (sender:anyobject) {                var webservice = Ocwebservice ()// The call to WebService is implemented mainly in the class Ocwebservice this OC        , Webservice.query (phonenumber.text)//Call the Query method to start accessing WebService, The parameter passed is the phone number;    }


(6) Run the program to see the effect.



The project Demo:http://pan.baidu.com/s/1hqgwnji. In the future I will not struggle to choose Swift or OC.




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

iOS mixed programming using SWIFT+OBJECTIVE-C call WebService

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.