我有以下函数调用:
@IBAction func submitCourse(sender: AnyObject) {
// print("Enter")
getTime( (courseName.text!), courseCode: (codeName.text!))
print(classes[0].end);
//print("ASODASODJASDJASASDASDD \(string1)")
}
自定义数据类:
class ClassSchedule {
var course: String?
var code: String?
var section: String?
var start: String?
var end: String?
init(course: String, code: String, section: String, start: String, end: String)
{
self.course = course
self.code = code
self.section = section
self.start = start
self.end = end
}
}
请求JSON对象,将其解析为classSchedule
:
// Read the JSON
do {
let data: NSData? = NSData(contentsOfURL: url)
if let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
{
//////ARRAY///////
let dataArray = jsonResult["data"] as! NSArray
//////
let arrayLength = dataArray.count
var count = 0
print("TOTAL OF CLASSES: \(arrayLength)");
for item in dataArray
{
classes.append(ClassSchedule(course: "TEMP", code: "TEMP", section: "TEMP", start:"TEMP", end:"TEMP") )
classes[count].course = item["subject"] as! String
classes[count].code = item["catalog_number"] as! String
classes[count].section = item["section"] as! String
print("Subject: \(classes[count].course!) \(classes[count].code!)");
print("Section: \(classes[count].section!)");
// print("Section: \(section_numb)");
let subjectArray = item["classes"] as! NSArray
for item2 in subjectArray{
let dateDictionary = item2["date"] as! NSDictionary
//let startTime = dateDictionary["start_time"]!
//self.performSelectorOnMainThread("updateIPLabel:", withObject: startTime, waitUntilDone: false)
//let endTime = dateDictionary["end_time"]!
classes[count].start = dateDictionary["start_time"] as! String
classes[count].end = dateDictionary["end_time"] as! String
string1 = classes[count].start!
print("START TIME: \(classes[count].start!)");
print("End Time: \( classes[count].end!)");
print("")
count += 1
print(count)
}
}
//let subject = dataArray["subject"]
}
} catch {
print("bad things happened")
}
print("ASDIAWDWD: \(classes[0].section)")
// print("ASDIAWDWASDASDD: \(classes[1].section)")
}).resume()
函数中的那些print语句工作正常并打印想要的数据。
我无法将填充的ClassSchedule
数组返回到ViewController.swift
。
我尝试将数组声明为全局变量,但它仍然在print(classes[0].end);
处给出错误,指出数组索引超出范围。
我感觉这是由于JSON的异步请求,但不知道如何修复它。
答案 0 :(得分:0)
是。那是因为它是一个异步调用。您必须在API调用成功中保留本地数组,并且在所有处理之后,您必须具有回调以将数据发送回调用者。也就是说,在进行API调用时,你必须有一个块作为参数。
<强>更新强>
user_groups