它是从某个网站获取天气信息的程序的一部分。 进入程序我使用singleton获取Core Data上下文。 AirportsICA和AirportsData是核心数据子类。 此函数必须解析页面并将所有数据保存到Core Data上下文,它在解析数据时工作正常,但在尝试将结果保存到数据库时抛出错误。怎么解决?有任何想法吗。
2017-03-16 23:56:21.197036天气应用[3603:81353] [通用] _BSMachError:端口700f; (os / kern)无效功能(0x14)“无法插入COPY_SEND”
2017-03-16 23:56:21.197265 Weather App [3603:81353] [Common] _BSMachError:port 700f; (os / kern)无效名称(0xf)“无法解除分配发送权”
func getData(forICAO icaoCode: String) -> Bool {
let config = URLSessionConfiguration.default
let apiKey = "zzzzzzzzz-zzzz-zzzz-zzzz-zzzzzz"
let url = URL(string: "https://somesite.com/current-conditions-list?api_key=" + apiKey + "&airports=" + icaoCode + "&states=&format=json")
let session = URLSession(configuration: config)
let task = session.dataTask(with: url!) { (data, responce, error) in
if error == nil && data != nil {
if let parsedDataArray = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! Array<Any> {
if let parsedData = parsedDataArray[0] as? Dictionary<String, Any> {
guard let airport = parsedData["airport"] as? String else { return }
guard let airport_name = parsedData["airport_name"] as? String else { return }
let updatedByUser = Date()
// Core Data
let context = CoreDataManager.instance.persistentContainer.viewContext
let entityForAirportICAO = NSEntityDescription.entity(forEntityName: "AirportsData", in: context)
let airportICAO = AirportsICAO(entity: entityForAirportICAO!, insertInto: context)
airportICAO.airport = airport
airportICAO.airport_name = airport_name
airportICAO.updatedByUser = updatedByUser
try! context.save()
}
}
}
}
task.resume()
return true
}
答案 0 :(得分:0)
在后台队列上调用URLSession.dataTask(with:completionHandler:)
的完成处理程序块,但是您正在从该块访问视图上下文。只应从主线程访问视图上下文。
相反,您应该使用后台任务:
CoreDataManager.instance.persistentContainer.performBackgroundTask() { context in
let entityForAirportICAO = NSEntityDescription.entity(forEntityName: "AirportsData", in: context)
let airportICAO = AirportsICAO(entity: entityForAirportICAO!, insertInto: context)
airportICAO.airport = airport
airportICAO.airport_name = airport_name
airportICAO.updatedByUser = updatedByUser
try! context.save()
}