从 coreData 加载图像时崩溃
Posted
技术标签:
【中文标题】从 coreData 加载图像时崩溃【英文标题】:Crash when loading images from coreData 【发布时间】:2016-10-15 09:36:17 【问题描述】:当我启动我的应用程序时,我从我的服务器下载了几张照片,然后像这样保存到 coreData(我按照本教程操作:Saving Picked Image to CoreData)
extension NewsFeedViewController
func getContext()
saveQueue.sync
let appDelegate = UIApplication.shared.delegate as! AppDelegate
self.managedContext = appDelegate.persistentContainer.viewContext
extension NewsFeedViewController
func prepareImageForSaving(image:UIImage)
// use date as unique id
let date : Double = NSDate().timeIntervalSince1970
// dispatch with gcd.
convertQueue.async()
print("dd")
// create NSData from UIImage
guard let imageData = UIImageJPEGRepresentation(image, 1) else
// handle failed conversion
print("jpg error")
return
// scale image, I chose the size of the VC because it is easy
// send to save function
self.saveImage(imageData: imageData as NSData, date: date)
extension NewsFeedViewController
func saveImage(imageData:NSData, date: Double)
saveQueue.async(flags: .barrier)
// create new objects in moc
guard let moc = self.managedContext else
return
guard let fullRes = NSEntityDescription.insertNewObject(forEntityName: "Blogger", into: moc) as? FullRes else
// handle failed new object in moc
print("moc error")
return
//set image data of fullres
fullRes.imageData = imageData as Data
// save the new objects
do
try moc.save()
catch
fatalError("Failure to save context: \(error)")
// clear the moc
moc.refreshAllObjects()
extension NewsFeedViewController
func loadImages(_ fetched:@escaping (_ images:[FullRes]?) -> Void)
saveQueue.async()
guard let moc = self.managedContext else
return
let fetchRequest :NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "FullRes")
//let fetchRequest = NSFetchRequest(entityName: "FullRes")//NSFetchRequest(entityName: "FullRes")
print(fetchRequest)
do
let results = try moc.fetch(fetchRequest)
let imageData = results as? [FullRes]
DispatchQueue.main.async()
fetched(imageData)
catch let error as NSError
print("Could not fetch \(error), \(error.userInfo)")
return
在该代码中我正在准备要保存的图像 - 保存它,然后在我的代码的其他部分(未在此处发布)并检查是否有互联网连接。如果没有加载图像,那么我调用上面发布的 loadImages() 函数。
调用它时出现此错误:
如果有人能帮我解决这个问题,不胜感激!
【问题讨论】:
【参考方案1】:我把let fetchRequest
改成了这个
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = FullRes.fetchRequest()
【讨论】:
【参考方案2】:您的代码没有问题。我已经实现了您的确切代码,并且运行良好。您现在应该尝试隔离您的问题。尝试评论使用 Internet 的功能,例如处理登录用户和下载内容的功能。
同时检查您的 AppDelegate 是否存在在您的应用在没有互联网的情况下启动时可能导致早期崩溃的功能。
始终尝试捕获因缺少可达性而导致的异常。
为此,我使用了以下函数:
import Foundation
import SystemConfiguration
open class Reachability
class func isConnectedToNetwork() -> Bool
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress ,
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
) else
return false
var flags : SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags)
return false
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
调用者:
if Reachability.isConnectedToNetwork() == true
//execute your code
else
//catch print
【讨论】:
以上是关于从 coreData 加载图像时崩溃的主要内容,如果未能解决你的问题,请参考以下文章
从 Assets.xcassets 加载图像时 iOS 应用程序崩溃