2017-02-11 49 views
2

你好,我是新來的斯威夫特和SOAP,我米使用http://www.webservicex.net/globalweather.asmx並得到響應,posts我想打印responsemyTableViewController請幫助三江源
響應我想打印SOAP響應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 
} 
+0

請問您發送演示?如果你不介意,我會檢查它並用解決方案返回給你 –

+0

oky Thankyou我現在發送 – ViralRathod

+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() 
} 
+0

你好,三江源回覆,但在'self.reloadData其遇到錯誤()''類型的值「myTableViewController」沒有成員「reloadData'' – ViralRathod

+0

@ViralRathod,請嘗試編輯答案 – KrishnaCA

+0

@ KrishnaCA NOP對不起錯誤'致命錯誤:意外地發現零,而展開一個可選值' – ViralRathod