简体   繁体   中英

Swift - Segue not being passed correct data

pretty new at swift. Currently, I have a program where on the click of a button I make an NSURL request, take that response, parse the XML, and store the data I need into a array[String]. Pressing this button also serves as a segue into a table view controller which will be dynamically populated with the info from the array.

What I'm seeing is that the segue is occurring and the next VC is being passed an empty array before my request is even complete and response is parsed. (this is all based on the print statements I've inserted in just about every other line to track the execution of my code).

How can I go about this so that the segue does not take me to the next VC until my response has been parsed?

class start: UIViewController, NSURLConnectionDelegate, NSXMLParserDelegate  {

var timeArr:[String] = []
var url = "myurl.com" 
@IBOutlet weak var get2: UIButton!
@IBAction func getAction(sender: UIButton) {


    var request = NSMutableURLRequest(URL: NSURL(string: url)!)
    httpGet (request) {
        (data, error) -> Void in
        if error != nil {
            print(error)
            mainInstance.arrivalArr.append("no arrival times")
        } else {
            self.beginParsing()
            print(data)
        }
    }
}


func httpGet(request: NSURLRequest!, callback: (String, String?) -> Void) {
    var session = NSURLSession.sharedSession()
    var task = session.dataTaskWithRequest(request){
        (data, response, error) -> Void in
        if error != nil {
            callback("", error!.localizedDescription)
        } else {
            var result = NSString(data: data!, encoding:
                NSUTF8StringEncoding)!
            self.data2 = data!
            callback(result as String, nil)
        }
    }
  task.resume()
}


func beginParsing()
{
    posts = []
    parser = NSXMLParser(data: data2)
    parser.delegate = self
    parser.parse()
}

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
{
    element = elementName
    if (elementName as NSString).isEqualToString("prd")
    {
        // more code
    }
}

func parser(parser: NSXMLParser, foundCharacters string: String)
{
    if element.isEqualToString("prdtm") {
        //code 

    }
}

func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
{
    if (elementName as NSString).isEqualToString("prd") {
        if !title1.isEqual(nil) {
            //code
        }

       //code
        finalTimeStr = getTime(finalTimeStr)
        timeArr.append(finalTimeStr)

    }
}



func getTime (time: String) -> String{
    var arrivalTime = time
    //code to trim and format time here
    var timeA = getTimeDiff(arrivalTime)
    timeA = trimToMin(timeA)
    return timeA
}



func trimToMin (timeToTrim : String) -> String {
    var timeInMin = timeToTrim
    //code to trim to minutes
    return substring2
}

func getTimeDiff (time: String) -> String{
    //code to find time difference
    let ret = stringFromTimeInterval(diff)       
    return ret
}

func stringFromTimeInterval(interval: NSTimeInterval) -> String {
    //code to format interval
    return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let CDview = segue.destinationViewController as? ListView {
        CDview.timeArr = timeArr
        //CDview.timeArr = mainInstance.arrivalArr
    }
}


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

override func viewWillAppear(animated: Bool) {
   timeArr = testArr

}

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

} Not sure where I went wrong. It's particularly confusing because if I use hardcoded strings and jump straight into getTimeDiff then it works perfectly fine and my table view on the next VC also looks great. Would appreciate any help. I've literally moved this code around for the last 12 hours trying to understand why it's not working.

Add a segue from view controller ( and not from UIButton) in storyboard . And name it as you want ( storyboard identifier ) . Perform the segue programmatically with performSegue(...) after you parsed the data .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM