我想打印soap响应myTableViewController

时间:2017-02-11 06:15:49

标签: ios swift web-services soap

您好我是Swift和SOAP的新手,我正在使用http://www.webservicex.net/globalweather.asmx并得到posts的回复我想将此response打印到myTableViewController请帮助谢谢你/> 回复

{Country = ""GetCitiesByCountryResult = "<NEWDATASET><TABLE><COUNTRY>NEPAL</COUNTRY><CITY>BHAIRAWA AIRPORT</CITY></TABLE><TABLE><COUNTRY>NEPAL</COUNTRY><CITY>JUMLA</CITY></TABLE><TABLE><COUNTRY>NEPAL</COUNTRY><CITY>KATHMANDU AIRPORT</CITY></TABLE><TABLE><COUNTRY>NEPAL</COUNTRY><CITY>POKHARA AIRPORT</CITY></TABLE><TABLE><COUNTRY>NEPAL</COUNTRY><CITY>SIMRA AIRPORT</CITY></TABLE><TABLE><COUNTRY>NEPAL</COUNTRY><CITY>SURKHET</CITY></TABLE><TABLE><COUNTRY>NEPAL</COUNTRY><CITY>TAPLEJUNG</CITY></TABLE><TABLE><COUNTRY>NEPAL</COUNTRY><CITY>BIRATNAGAR AIRPORT</CITY></TABLE></NEWDATASET>";}    

ViewController.swift

import UIKit
class ViewController:UIViewController,XMLParserDelegate,UITextFieldDelegate,NSURLConnectionDelegate, UITableViewDelegate  {

@IBOutlet var CountryName: UITextField!

var parser = XMLParser()
var posts = NSMutableArray()
var elements = NSMutableDictionary()
var element = NSString()
var title1 = NSMutableString()
var date = NSMutableString()
var xmlData = NSMutableData()

func beginParsing()
{
    posts = []
    parser = (XMLParser(data:xmlData as Data))
    parser.delegate = self
    parser.parse()
    //tbData!.reloadData()
    for element in posts {
        print(element)
    }

    performSegue(withIdentifier: "myTableView", sender:posts)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let guest = segue.destination as! myTableViewController

    guest.city = posts
}

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
{
    element = elementName as NSString

    if (elementName as NSString).isEqual(to: "GetCitiesByCountryResponse")
    {
        elements = NSMutableDictionary()
        elements = [:]
        title1 = NSMutableString()
        title1 = ""
        date = NSMutableString()
        date = ""
    }
}

func parser(_ parser: XMLParser, foundCharacters string: String)
{
    let data = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()

    let str = data.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)

    if element.isEqual(to: "GetCitiesByCountryResult") {

        title1.append(str)


    } else if element.isEqual(to: "Country") {
        date.append(str)
    }
}

 func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
{
    if (elementName as NSString).isEqual(to: "GetCitiesByCountryResponse") {
        if !title1.isEqual(nil) {
            elements.setObject(title1, forKey: "GetCitiesByCountryResult" as NSCopying)
        }
        if !date.isEqual(nil) {
            elements.setObject(date, forKey: "Country" as NSCopying)
        }

        posts.add(elements)
    }
}


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func invoke(_ sender: Any) {

    let country = CountryName.text

    let is_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><GetCitiesByCountry xmlns='http://www.webserviceX.NET'><CountryName>\(country!)</CountryName></GetCitiesByCountry></soap:Body></soap:Envelope>")

    let is_URL: String = "http://www.webservicex.net/globalweather.asmx"

    let lobj_Request = NSMutableURLRequest(url: NSURL(string: is_URL)! as URL)
    let session = URLSession.shared

    lobj_Request.httpMethod = "POST"
    lobj_Request.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)

    lobj_Request.addValue("www.webservicex.net", forHTTPHeaderField: "Host")

    lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")

    lobj_Request.addValue(String (is_SoapMessage), forHTTPHeaderField: "Content-Length")

    lobj_Request.addValue("http://www.webserviceX.NET/GetCitiesByCountry", forHTTPHeaderField: "SOAPAction")

    let task = session.dataTask(with: lobj_Request as URLRequest, completionHandler: {data, response, error -> Void in

        print("response = \(response)")




         let xmlData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)


        self.xmlData = NSMutableData(data: data!)

        print("Body: \(xmlData)")

        self.beginParsing()

       print("Status is = \(self.date)")

        if error != nil
        {
            print("Error: ")
        }

    })
    task.resume()

}

}

myTableViewController.swift

class myTableViewController: UIViewController , UITableViewDataSource , UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!

var city = NSMutableArray()

override func viewDidLoad() {
    super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    tableView!.reloadData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int
{
    return city.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    var cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
    if(cell.isEqual(NSNull.self)) {
        cell = Bundle.main.loadNibNamed("Cell", owner: self, options: nil)?[0] as! UITableViewCell;
    }

    cell.textLabel?.text = ((city.object(at: indexPath.row) as AnyObject).value(forKey:"title") as! NSString) as String
    cell.detailTextLabel?.text = ((city.object(at: indexPath.row) as AnyObject).value(forKey:"date") as! NSString) as String

    return cell as UITableViewCell
}

1 个答案:

答案 0 :(得分:1)

检查完代码后,我发现您的问题是您没有正确解析XML数据。

获取“GetCitiesByCountryResult”的值后,您可以将其转换为xml数据并再次解析以获取所有城市的列表作为数组。之后,您可以将其传递给viewcontroller以获得更多结果

let xmlArray = posts.value(forKey: "GetCitiesByCountryResult") as! [String]
let xmlString: String = xmlArray[0]

if let xml_Data:Data = xmlString.data(using: String.Encoding.utf8) {
    parser = XMLParser(data: xml_Data)
    parser.delegate = self
    parser.parse()
}