How about, I have a problem, my application with Xcode 7.3.1 ran perfectly, since I updated Xcode 8 my application was updated and the code was automatically converted, I got some errors but I could fix them, I run my app but when I try to open a UITableView that brings data from a MySQL database the application dies.
This is the code in which the line:
jsonResult = try JSONSerialization.jsonObject(with: self.data as Data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSMutableArray
It is the one that gives error.
In console I get this error:
Data downloaded
Could not cast value of type '__NSArrayI' (0x1035ffc08) to 'NSMutableArray' (0x1035ffcd0).
I enclose the complete code of that file
import Foundation
protocol HomeModelProtocal: class {
func itemsDownloaded(_ items: NSArray)
}
class HomeModel: NSObject, URLSessionDataDelegate {
weak var delegate: HomeModelProtocal!
var data : NSMutableData = NSMutableData()
let urlPath: String = "http://localhost/iosws/lista_docentes.php"
func downloadItems() {
let url: URL = URL(string: urlPath)!
var session: Foundation.URLSession!
let configuration = URLSessionConfiguration.default
session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTask(with: url)
task.resume()
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
self.data.append(data);
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if error != nil {
print("Failed to download data")
}else {
print("Data downloaded")
self.parseJSON()
}
}
func parseJSON() {
var jsonResult: NSMutableArray = NSMutableArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: self.data as Data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSMutableArray
} catch let error as NSError {
print(error)
}
var jsonElement: NSDictionary = NSDictionary()
let locations: NSMutableArray = NSMutableArray()
for i in 0..<jsonResult.count
{
jsonElement = jsonResult[i] as! NSDictionary
let location = LocationModel()
if let iddocente = jsonElement["iddocente"] as? String,
let nombres = jsonElement["nombres"] as? String
{
location.iddocente = iddocente
location.nombres = nombres
}
locations.add(location)
}
DispatchQueue.main.async(execute: { () -> Void in
self.delegate.itemsDownloaded(locations)
})
}
}