Alamofire for循环在Playgrounds中返回空数组

时间:2017-04-29 09:05:40

标签: swift alamofire

我已经搜索了最后一小时,我似乎无法弄清楚这一点。我放弃了并且问道。

我在下面有以下操场脚本,它会打印一个空数组。

我想在调用函数时返回一个自定义对象数组。我读到Alamofire是异步的,但我现在还不知道该怎么做。

提前致谢!

//: Playground - noun: a place where people can play

import UIKit
import Alamofire
import SWXMLHash
import PlaygroundSupport
import Foundation


PlaygroundPage.current.needsIndefiniteExecution = true
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)

class Tram {

    var arrivalInMinutes: Int?
    var tramDestinationEnglish: String?

    init(destination: String, arrivalTime: Int) {
        tramDestinationEnglish = destination
        arrivalInMinutes = arrivalTime

    }
}

func retrieveListOfTrams() -> [Tram] {

    var anyArray = [Tram]()

    Alamofire.request("https://hktramways.com/nextTram/geteat.php?stop_code=08W")
        .response { (response) in

            let xmlData = SWXMLHash.parse(response.data!)

            for elem in xmlData["root"]["metadata"].all {
                let tramArrival = elem.element!.attribute(by: "arrive_in_minute")!.text
                let tramDestination = elem.element!.attribute(by: "tram_dest_en")!.text
                anyArray.append(Tram(destination: tramDestination, arrivalTime: Int(tramArrival)!))

                }

            }
    return anyArray


}

print(retrieveListOfTrams())

1 个答案:

答案 0 :(得分:1)

问题是您在请求返回结果之前返回数组,因为当您阅读Alamofire时会出现异步行为。解决此问题的一种方法是使用一个完成块,它只会在结果到达后返回数组:

func retrieveListOfTrams(completion: @escaping ([Tram]) -> Void) {

    var anyArray = [Tram]()

    Alamofire.request("https://hktramways.com/nextTram/geteat.php?stop_code=08W")
        .response { (response) in

            let xmlData = SWXMLHash.parse(response.data!)

            for elem in xmlData["root"]["metadata"].all {
                let tramArrival = elem.element!.attribute(by: "arrive_in_minute")!.text
                let tramDestination = elem.element!.attribute(by: "tram_dest_en")!.text
                anyArray.append(Tram(destination: tramDestination, arrivalTime: Int(tramArrival)!))

                }


            completion(anyArray)
            }   

}

然后你可以调用函数:

retrieveListOfTrams(completion: { anyArray in
    print(anyArray.description)
})