如何在swift中从xml响应中获取json数组

时间:2016-10-25 09:34:41

标签: swift

我是ios的新手。我正在使用soap请求制作简单的登录应用程序。 所以问题是当我从服务器得到响应时它看起来像是

Optional(<?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>
        <CreateLoginResponse xmlns="http://tempuri.org/">
            <CreateLoginResult>[{"DelBoyId":36,"DelBoy_Fname":"abc-xyz","Password":"123","DelBoy_Email":"abc@gmail.com","DelBoy_Contact":"123","RoleName":"Admin"}]
            </CreateLoginResult>
        </CreateLoginResponse>
    </soap:Body>
</soap:Envelope>).

我希望在会话中存储此键值[{"DelBoyId":36,"DelBoy_Fname":"abc-xyz","Password":"123","DelBoy_Email":"abc@gmail.com","DelBoy_Contact":"123","RoleName":"Admin"}]

我该怎么做?请帮帮我。

谢谢。

这是我的代码

import UIKit

class LoginPageViewController: UIViewController, NSXMLParserDelegate {

    @IBOutlet var txtUserEmail: UITextField!

    @IBOutlet var txtUserPassword: UITextField!

    var webData : NSMutableData?
    var parser : NSXMLParser?
    var flag : Bool?
    var capturedString : String?

    func processTerrorSaftyTips(data : NSData){
        parser = NSXMLParser(data: data)
        parser!.delegate = self
        parser!.parse()

    }


    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }


    @IBAction func loginButtonTapped(sender: AnyObject) {

        let mobile = txtUserEmail.text;
        let password = txtUserPassword.text;


        let soapMessage = String(format: "<?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><CreateLogin xmlns='http://tempuri.org/'><mobile>"+mobile!+"</mobile><pasword>"+password!+"</pasword></CreateLogin></soap:Body></soap:Envelope>");

        let url = NSURL(string: "http://23.91.115.57/nagifts/NaGiftsWebService.asmx");

        let theRequest = NSMutableURLRequest (URL: url!);
        let soapLength = String(soapMessage.characters.count)

        theRequest.addValue("text/xml", forHTTPHeaderField: "Content-Type");
        theRequest.addValue(soapLength, forHTTPHeaderField: "Content-Length")
        theRequest.HTTPMethod = "POST";
        theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion: false);

        let urlConnection = NSURLConnection(request: theRequest , delegate: self);

    }

    func connection(connection: NSURLConnection, didFailWithError error: NSError){

    }

    func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse){

        webData = NSMutableData()
    }
    func connection(connection: NSURLConnection, didReceiveData data: NSData){

        webData!.appendData(data)
    }
    func connectionDidFinishLoading(connection: NSURLConnection){

        processTerrorSaftyTips(webData!)
    }

    func parserDidStartDocument(parser: NSXMLParser){

        flag = false
        capturedString = ""
    }
    func parserDidEndDocument(parser: NSXMLParser){

    }

    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]){

        flag = false
        capturedString = ""
        if elementName == "CreateLoginResult"
        {
            flag = true
        }

    }

    func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?){

        flag = false
        if elementName == "CreateLoginResult"
        {
            print((capturedString!))


        }
    }
    func parser(parser: NSXMLParser, foundCharacters string: String){

        if flag! {
            capturedString = capturedString! + string
        }

    }
    func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError){

        }

}

1 个答案:

答案 0 :(得分:1)

Swift3:

声明任何数组,因为您的响应在数组中

var arrayFromResult = NSMutableArray()

接下来转到Parse DidEndElement并将findCharacters添加到Array这样做

 if elementName == "CreateLoginResult"
  {
        print((capturedString!))
    arrayFromResult.add(capturedString)

   }

使用数组或从数组中检索字典值

  for var i  in 0..<arrayFromResult.count {

        let dictFromArray = arrayFromResult.object(at: i) as! NSDictionary

        let name = dictFromArray.value(forKey: "DelBoy_Fname") as! String
        print(name)

        let password = dictFromArray.value(forKey: "Password") as! String
        print(password)


    }