我正在尝试使用Swift从JSON文件中获取值数组。我找到了使用IBAction方法按下按钮时打印值的方法。
函数在第一次按下按钮时正在打印数组但是,如果我再次按下按钮,应用程序崩溃会发出错误:
致命错误:在展开Optional值时意外发现nil (LLDB)
我第一次从打印jsonResult获得的数组看起来像:
1: {
Age = 30;
Email = "info@example.com";
Location = Rome;
MyText = "Design Agency";
Name = Admin;
Password = 123456;
REF = 002;
"Reg_Date" = "2015-07-28";
Sex = Male;
Surname = "Mobile App"; }
2: {
Age = 30;
Email = "example@gmail.com";
Location = London;
MyText = "aaaaaaaaa";
Name = Andrew;
Password = 123456;
REF = 001;
"Reg_Date" = "2015-07-28";
Sex = Male;
Surname = Nos; }
似乎第二次调用该函数时,它无法再读取该文件。 我的代码有什么问题?我需要关闭连接吗?
@IBAction func login_button(sender: AnyObject) {
searchFunction()
}
func searchFunction() {
var tempUrlValue = loginJsonResults.stringForKey("loginJsonResults")
let urlPath: String = "https://example.com/iOS/users_result.json"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
var err: NSError
var jsonResult: NSMutableArray = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSMutableArray
//Call jsonResult Values
var temporaryString: AnyObject = jsonResult[1]
for (index, jsonResult) in enumerate(jsonResult){
println("\(index + 1): \(jsonResult)")
countUsers++
}
println(countUsers)
}