我有一个函数,在我调用它之后,它会不断地调用函数(一旦for循环完成了stocks.count,函数将从0重新开始,以无限循环到达stocks.count并访问http,导致http在几分钟后停止响应,然后崩溃应用程序。我已经尝试添加一个计时器,甚至在执行一个函数后执行一个segue(它改变了页面,但函数仍然在调用http)。但没有什么能使功能停止。我很感激任何帮助,因为这个问题在3周内被困在这个问题上:(
我按如下方式调用该函数:
self.downloadStockPrice({ () -> () in
}, stocks: stocks)
这就是功能本身:
func downloadStockPrice(completed: DownloadComplete, stocks: [Stock]) {
for x in 0 ..< stocks.count {
let stock = stocks[x].stock
let requestURL: NSURL = NSURL(string: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22\(stock)%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&format=json")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("Everyone is fine, file downloaded successfully.")
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let queryDict = json["query"] as? Dictionary<String, AnyObject> {
if let resultsDict = queryDict["results"] as? Dictionary<String, AnyObject> {
if let quoteDict = resultsDict["quote"] as? Dictionary<String, AnyObject> {
let bidString = quoteDict["Bid"] as? String
DataService.ds.REF_BASE.child("stocks").child(stock).child("lastPrice").setValue(Float(bidString!))
}
}
}
}catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
}
}