在swift3中为PickerView添加响应值

时间:2017-03-25 08:21:53

标签: ios swift3 uipickerview

我的项目中有4个选择器,其中一个是"source"。我收到了商店的回复以及来源。我希望无论我收到什么作为回复,我都希望在我的pickerView中。

import UIKit

class bookTicketViewController: UIViewController, UIPickerViewDelegate,UIPickerViewDataSource,UITextFieldDelegate ,XMLParserDelegate{

    @IBOutlet var sourceTextField: UITextField!
    @IBOutlet var destinationTextField: UITextField!
    @IBOutlet var adultsTextField: UITextField!
    @IBOutlet var childTextField: UITextField!

    @IBOutlet weak var sourcePicker: UIPickerView!
    @IBOutlet weak var destinationPicker: UIPickerView!
    @IBOutlet weak var adultsPicker: UIPickerView!
    @IBOutlet weak var childPicker: UIPickerView!

    var source = NSMutableArray()
    var destination = ["Mumbai","Pune","Jaipur","Baroda","Goa"]
    var adults = ["1","2","3","4","5","6","7","8","9","10"]
    var child = ["0","1","2","3","4","5","6","7","8","9","10"]

    var parser = XMLParser()
    var parser1 = XMLParser()
    var posts = NSMutableArray()
    var posts1 = NSMutableArray()
    var elements = NSMutableDictionary()
    var element = NSString()
    var total_amount = NSMutableString()
    var xmlData = NSMutableData()
    var ticket_no = NSMutableString()
    var adultAmount = NSMutableString()
    var childAmount = NSMutableString()
    var source1 = NSMutableArray()
    var title1 = NSMutableString()

    var date = NSMutableArray()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.HelloWebService()
        print("Get ",self.source)

    }
    override func viewDidAppear(_ animated: Bool) {

    }


    @IBAction func confirmTicketSubmitButton(_ sender: Any) {

        self.service1()
       // self.service2()
    }

    func service1()
    {

        let source = sourceTextField.text
        let destination = destinationTextField.text
        let adults = adultsTextField.text
        let child = childTextField.text

        let is_SoapMessage  = String  (format :"<soapenv:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'><soapenv:Header/><soapenv:Body><ticket_amount soapenv:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'><SourceTextField xsi:type='xsd:string'>\(source!)</SourceTextField><DestinationTextField xsi:type='xsd:string'>\(destination!)</DestinationTextField><AdultsTextField xsi:type='xsd:int'>\(adults!)</AdultsTextField><ChildTextField xsi:type='xsd:int'>\(child!)</ChildTextField></ticket_amount></soapenv:Body></soapenv:Envelope>")

        let is_URL: String = "http://192.168.43.23/app/app/service/registrationService.php?wsdl"

        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("192.168.43.23", 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://192.168.43.23/app/app/service/registrationService.php/ticket_amount/ticket_amount", 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()

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

        })
        task.resume()
    }

    func HelloWebService()
    {
        let is_SoapMessage  = String  (format :"<soapenv:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'><soapenv:Header/><soapenv:Body><rout_detail soapenv:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/></soapenv:Body></soapenv:Envelope>")


        let is_URL: String = "http://192.168.43.23/app/app/service/registrationService.php?wsdl"

        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("192.168.43.23", 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://192.168.43.23/app/app/service/registrationService.php/rout_detail", 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("hello \(self.title1)")
            print("hello \(self.date)")

            self.source.add(self.date)

            print("Joom",self.source)

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

        })
        task.resume()
    }



    func beginParsing()
    {
        posts = []
        parser = (XMLParser(data:xmlData as Data))
        parser.delegate = self
        parser.parse()


        self.source.add(self.date)


//        DispatchQueue.main.async(execute: {
//            let storyboard = UIStoryboard(name: "Main", bundle: nil)
//            let destViewController = storyboard.instantiateViewController(withIdentifier: "confirmTicketView") as! confirmTicketViewController
//            destViewController.postTicketNo = "\(self.ticket_no)"
//            destViewController.postTotalAmount = "\(self.total_amount)"
//            destViewController.postAdultAmount = "\(self.adultAmount)"
//            destViewController.postChildAmount = "\(self.childAmount)"
//            destViewController.sourceData = self.sourceTextField.text!
//            destViewController.destinationData = self.destinationTextField.text!
//            destViewController.adultsData = self.adultsTextField.text!
//            destViewController.childData = self.childTextField.text!
//            
//            self.present(destViewController, animated: true, completion: nil)
//        });
    }


    // didStartElement
    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:"response")
        {
            elements = NSMutableDictionary()
            elements = [:]
           ticket_no = NSMutableString()
            ticket_no = ""
            total_amount = NSMutableString()
            total_amount = ""
            adultAmount = NSMutableString()
            adultAmount = ""
            childAmount = NSMutableString()
            childAmount = ""



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

        }
        //  print(String(format : "didStartElement / elementName %@", elementName))


    }

    // FoundCharacters

    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:"ticket_no") {
            ticket_no.append(string)
            print(ticket_no)
        }
        if element.isEqual(to:"total_amount") {
            total_amount.append(string)
            print(total_amount)
        }
        if element.isEqual(to:"adultAmount") {
            adultAmount.append(string)
        }
            if element.isEqual(to:"childAmount") {
                childAmount.append(string)
        }
            else if element.isEqual(to: "item") {


                self.date.add(str)
        }

    }

    // DidEndElement
    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
    {
        //  print(String(format : "didEndElement / elementName %@", elementName))
        if (elementName as NSString).isEqual (to:"response") {
            if !ticket_no.isEqual(nil) {
                elements.setObject(ticket_no, forKey:"ticket_no" as NSCopying)
            }
            if !total_amount.isEqual(nil) {
                elements.setObject(total_amount, forKey:"total_amount" as NSCopying)
            }
            if !adultAmount.isEqual(nil) {
                elements.setObject(adultAmount, forKey:"adultAmount" as NSCopying)
            }
            if !childAmount.isEqual(nil) {
                elements.setObject(childAmount, forKey:"childAmount" as NSCopying)
            }

            posts.add(elements)
        }
        if (elementName as NSString).isEqual(to: "source")
        {


            if !date.isEqual(nil) {
                elements.setObject(date, forKey: "item" as NSCopying)
            }
            posts.add(elements)
        }
    }
    func numberOfComponents(in pickerView: UIPickerView) -> Int
    {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        var countrows: Int = self.source.count

        if pickerView == sourcePicker
        {
            countrows = self.source.count
        }
        if pickerView == destinationPicker
        {
            countrows = self.destination.count
        }
        if pickerView == adultsPicker
        {
            countrows = self.adults.count
        }
        if pickerView == childPicker
        {
            countrows = self.child.count
        }
        return countrows
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {



        print("get source1",self.source)

        if pickerView == sourcePicker
        {
            self.view.endEditing(true)
            return self.source[row] as? String
        }
        else if pickerView == destinationPicker
        {
            self.view.endEditing(true)
            return destination[row]
        }
        else if pickerView == adultsPicker
        {
            self.view.endEditing(true)
            return adults[row]
        }
        else if pickerView == childPicker
        {
            self.view.endEditing(true)
            return child[row]
        }
        return ""
    }


    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if pickerView == sourcePicker   {

            self.sourceTextField.text = self.source[row] as? String
            self.sourcePicker.isHidden = true
        }
        else if pickerView == destinationPicker   {
            self.destinationTextField.text = self.destination[row]
            self.destinationPicker.isHidden = true
        }
        else if pickerView == adultsPicker   {
            self.adultsTextField.text = self.adults[row]
            self.adultsPicker.isHidden = true
        }
        else if pickerView == childPicker   {
            self.childTextField.text = self.child[row]
            self.childPicker.isHidden = true
        }
    }


    func textFieldDidBeginEditing(_ textField: UITextField)
    {
        if textField == self.sourceTextField
        {
            self.sourcePicker.isHidden = false
            textField.endEditing(true)
        }
        if textField == self.destinationTextField
        {
            self.destinationPicker.isHidden = false
            textField.endEditing(true)
        }
        if textField == self.adultsTextField
        {
            self.adultsPicker.isHidden = false
            textField.endEditing(true)
        }
        if textField == self.childTextField
        {
            self.childPicker.isHidden = false
            textField.endEditing(true)
        }
    }}

我的店铺回复

(
    RAJKOT,
    AHMEDABAD,
    SURAT,
    VAPI,
    MUMBAI,
    PUNE,
    JAIPUR,
    BARODA,
    GOA
)

1 个答案:

答案 0 :(得分:1)

您只需要重新加载pickerview

sourcePicker.reloadAllComponents()