Здесь я загружаю данные JSON и сохраняю их в основных данных для автономного магазина.При отображении данных JSON в tableView он отлично работает для меня.Но когда я получаю данные JSON из основных данных, я получаю текст, но не могу отобразить изображения в tableView, почему?Может кто-нибудь, пожалуйста, помогите мне в следующем коде
import UIKit
import CoreData
struct JsonData {
var nameS: String?
var picS: String?
var spouseS: String?
init(name: String, image: String, spouse: String) {
self.nameS = name
self.picS = image
self.spouseS = spouse
}
}
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var iteamsArray = [JsonData]()
override func viewDidLoad() {
fetchData()
}
func downloadJsonwithImages() {
let urlStr = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors"
let url = URL(string: urlStr)
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
guard let respData = data else {
return
}
guard error == nil else {
print("error")
return
}
do{
let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
let actors = jsonObj["actors"] as! [[String: Any]]
for actor in actors {
let name = actor["name"] as! String
let pic = actor["image"] as! String
let spouse = actor["spouse"] as! String
self.iteamsArray.append(JsonData(name: name, image: pic, spouse: spouse))
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch {
print("catch error")
}
}).resume()
self.saveCoreData()
}
func saveCoreData(){
let urlStr = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors"
let url = URL(string: urlStr)
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
guard let respData = data else {
return
}
guard error == nil else {
print("error")
return
}
do{
let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
let actors = jsonObj["actors"] as! [[String: Any]]
for actor in actors {
let name = actor["name"] as! String
let pic = actor["image"] as! String
let spouse = actor["spouse"] as! String
let coreData = NSEntityDescription.insertNewObject(forEntityName: "Actor", into: self.context) as! Actor
coreData.name = name
coreData.spouse = spouse
//Converting NSString to NSData
let picNSData = pic.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
//assigning NSData value to core data attribute
coreData.image = picNSData as NSData
print("core data saved images \(coreData.image!)")
}
try self.context.save()
}
catch {
print("catch error")
}
}).resume()
}
func fetchData() {
do {
let fetchRequest : NSFetchRequest<Actor> = Actor.fetchRequest()
let actors = try context.fetch(fetchRequest)
if actors.count > 0 {
for actor in actors as [Actor] {
let nameCore = actor.value(forKey: "name")
let spouseCore = actor.value(forKey: "spouse")
//here imageData contains nsdata
let imageData = actor.value(forKey: "image")
//converting NSData to String for append JsonData Struct
let imageCore = String(describing: imageData)
print("we r in fetch image.. \(imageCore)")
self.iteamsArray.append(JsonData(name: nameCore as! String, image: imageCore , spouse: spouseCore as! String))
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
else {
downloadJsonwithImages()
}
} catch { print(error) }
}
func loadImageFrom(URL url:String, forImage imageView:UIImageView) {
DispatchQueue.global(qos: .userInteractive).async {
//when i run second time means its fetching from core data cell.picImageview.image != nil
let data = NSData(contentsOf: URL(string: url)!)//fatal error: unexpectedly found nil while unwrapping an Optional value
DispatchQueue.main.sync {
imageView.image = UIImage(data: data! as Data)
}
}
}
}
// MARK: - TableView
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return iteamsArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "JsonCell", for: indexPath) as! JsonTableViewCell
let aData = iteamsArray[indexPath.row]
cell.labelName.text = aData.nameS
cell.labelUsername.text = aData.spouseS
if cell.picImageview.image == nil {
self.loadImageFrom(URL: aData.picS!, forImage: cell.picImageview)
}else {
//what should i do to fetch from core data
self.loadImageFrom(URL: aData.picS!, forImage: cell.picImageview)
}
cell.selectionStyle = .none
return cell
}
}
Пожалуйста, помогите мне получить изображения из основных данных в таблицу.