Unable to show image form Core data on offline Mode In swift UI - swift

I am using AsyncImage to download the image and display it into view. I have created the respective properties into core data including image type is string to save the data locally . I am trying to load the into offline mode , it was able to show the rest of the properties without Image and it showing blank ..
Here is the code for Core Data manager .
class CoreDataManager {
let persistentContainer: NSPersistentContainer
static let shared: CoreDataManager = CoreDataManager()
private init() {
persistentContainer = NSPersistentContainer(name: "ReditModel")
persistentContainer.loadPersistentStores { description, error in
if let error = error {
// fatalError("Unable to initialize Core Data \(error)")
print("Unable to save the data :\(error.localizedDescription)")
}
}
}
}
Here is the code for main ..
#main
struct CoreDataDemoApp: App {
#StateObject private var viewModel = RedditViewModel()
let persistentContainer = CoreDataManager.shared.persistentContainer
var body: some Scene {
WindowGroup {
ContentView().environment(\.managedObjectContext, persistentContainer.viewContext).environmentObject(viewModel)
}
}
}
Here is the view model..
#MainActor
class RedditViewModel: ObservableObject {
#Published private(set) var stories = [Story]()
private var redditService: RedditService
init(redditService: RedditService = RedditService()) {
self.redditService = redditService
}
// Swift 5.5
func fetchData(viewContext: NSManagedObjectContext) async {
let url = NetworkURLs.urlBase
do {
let response = try await redditService.getModel(from: url)
let stories = response.data.children.map { $0.data }
self.stories = stories
saveRecord(viewContext: viewContext)
} catch (let error) {
print(error)
}
}
public func saveRecord(viewContext: NSManagedObjectContext) {
do {
stories.forEach { story in
let redit = ReditEntity(context: viewContext)
redit.title = story.title
redit.numComments = Int64(story.numComments)
redit.score = Int64(story.score)
redit.urlImage = story.thumbnail
}
try viewContext.save()
} catch {
print(error.localizedDescription)
}
}
}
Here is the code for Row view .
struct RowView: View {
#EnvironmentObject var viewModel: RedditViewModel
let title: String
let comments: String
let score: String
let urlImage: String?
var body: some View {
VStack(alignment: .leading) {
HStack {
if let urlImage = urlImage, urlImage.contains("https"), let url = URL(string: urlImage) {
AsyncImage(url: url)
}
VStack(alignment: .leading) {
HeadTitleView(title: title)
Text("Comments: \(comments)")
Text("Score: \(score)")
Spacer()
}
}
}
}
}
Here is the content view ..
struct ContentView: View {
#EnvironmentObject private var viewModel: RedditViewModel
#Environment(\.managedObjectContext) private var viewContext
#FetchRequest(entity: ReditEntity.entity(), sortDescriptors: [])
private var dbStories: FetchedResults<ReditEntity>
var dbFatchReditRecord: NSFetchRequest<ReditEntity> = ReditEntity.fetchRequest()
var body: some View {
VStack {
Text("Reddit Service")
.font(.largeTitle)
List {
ForEach(dbStories) { story in
// custom cell
RowView(title: story.title ?? "", comments: "\(story.numComments)", score: "\(story.score)", urlImage: story.urlImage)
}
}
}
.onAppear {
if dbStories.isEmpty {
Task {
await viewModel.fetchData(viewContext: viewContext)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
let persistedContainer = CoreDataManager.shared.persistentContainer
ContentView().environment(\.managedObjectContext, persistedContainer.viewContext) }
}
Here is the screenshot when I run the app on Offline model ..

Out of curiosity: How are you supposed to be able to load a https url while being offline?
-> urlImage.contains("https")
You should download the image and store it on your local file system. For example give your data model 2 attributes: offlineUrlString and onlineUrlString. Then as a fallback if the online url results in an empty image, then use the offline image. Once you are online again, update the offline image again.

Related

Swift UI unable to fetch data form Core Data

I am trying to save and fetch data form core data by using swift UI . I debug the code , I can see the the data is saved into core data and it has 5 record but the problem is when I tried to reload and re-run it it showing only one record.
Here is the code View Model ..
import Foundation
import CoreData
#MainActor
class RedditViewModel: ObservableObject {
#Published private(set) var stories = [Story]()
private var redditService: RedditService
init(redditService: RedditService = RedditService()) {
self.redditService = redditService
}
// Swift 5.5
func fetchData(viewContext: NSManagedObjectContext) async {
let url = NetworkURLs.urlBase
do {
let response = try await redditService.getModel(from: url)
let stories = response.data.children.map { $0.data }
self.stories = stories
saveRecord(viewContext: viewContext)
} catch (let error) {
print(error)
}
}
public func saveRecord(viewContext: NSManagedObjectContext) {
do {
let redit = ReditEntity(context: viewContext)
stories.forEach { story in
redit.title = story.title
redit.numComments = Int64(story.numComments)
redit.score = Int64(story.score)
redit.urlImage = story.thumbnail
}
try viewContext.save()
} catch {
print(error.localizedDescription)
}
}
}
Here is the code for main app ..
import SwiftUI
#main
struct CoreDataDemoApp: App {
#StateObject private var viewModel = RedditViewModel()
let persistentContainer = CoreDataManager.shared.persistentContainer
var body: some Scene {
WindowGroup {
ContentView().environment(\.managedObjectContext, persistentContainer.viewContext).environmentObject(viewModel)
}
}
}
Here is code into content view ..
import SwiftUI
import CoreData
struct ContentView: View {
#EnvironmentObject private var viewModel: RedditViewModel
#Environment(\.managedObjectContext) private var viewContext
#FetchRequest(entity: ReditEntity.entity(), sortDescriptors: [])
private var dbStories: FetchedResults<ReditEntity>
var dbFatchReditRecord: NSFetchRequest<ReditEntity> = ReditEntity.fetchRequest()
var body: some View {
VStack {
Text("Reddit Service")
.font(.largeTitle)
List {
ForEach(dbStories) { story in
// custom cell
RowView(title: story.title ?? "", comments: "\(story.numComments)", score: "\(story.score)", urlImage: story.urlImage)
}
}
}
.onAppear {
if dbStories.isEmpty {
Task {
await viewModel.fetchData(viewContext: viewContext)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
let persistedContainer = CoreDataManager.shared.persistentContainer
ContentView().environment(\.managedObjectContext, persistedContainer.viewContext) }
}
Here is the code for RowView.swift
import SwiftUI
struct RowView: View {
#EnvironmentObject var viewModel: RedditViewModel
let title: String
let comments: String
let score: String
let urlImage: String?
var body: some View {
VStack(alignment: .leading) {
HStack {
if let urlImage = urlImage, urlImage.contains("https"), let url = URL(string: urlImage) {
AsyncImage(url: url)
}
VStack(alignment: .leading) {
HeadTitleView(title: title)
Text("Comments: \(comments)")
Text("Score: \(score)")
Spacer()
}
}
}
}
}
Here is the code for Header.swift ..
import SwiftUI
struct HeadTitleView: View {
#EnvironmentObject var viewModel: RedditViewModel
let title: String
var body: some View {
Text(title)
}
}
Here is the screenshot ..
let redit = ReditEntity(context: viewContext)
stories.forEach { story in
redit.title = story.title
...
}
Here you are creating an entity object but then you reuse that same object inside the loop so what you end up doing is updating this single object with each story instead of creating a new object for each story.
Simply swap the lines to fix the problem
stories.forEach { story in
let redit = ReditEntity(context: viewContext)
redit.title = story.title
...
}

Error fetching abstract entity in preview

I have an abstract entity 'Animal' with a name attribute which is parent to two other entities 'Cat' and 'Dog'. I get the broken preview message in the canvas the moment I set fetchrequest to 'Animal' (works without problems setting any other entity or sub-entity)
Here's how Core Data stack is set up:
struct PersistenceController {
static let shared = PersistenceController()
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let viewContext = result.container.viewContext
let newCat = Cat(context: viewContext)
newCat.name = "Cat1"
let newDog = Dog(context: viewContext)
newDog.name = "Dog1"
do {
try viewContext.save()
} catch {
print(error.localizedDescription)
}
return result
}()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "Zoo")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error {
print(error.localizedDescription)
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
}
}
Main app file:
struct ZooApp: App {
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
}
And here's ContentView:
struct ContentView: View {
#Environment(\.managedObjectContext) var viewContext
#FetchRequest(sortDescriptors: []) var animals: FetchedResults<Animal>
var body: some View {
VStack {
ForEach(animals) { animal in
Text(animal.name ?? "")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
let persistenceController = PersistenceController.preview
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
I tried every possible answer I could find on the web (manually generating the class files and adding #objc(Entity) wrapper, setting module to current product module, changing the previews in every way, making the 'Animal' class non-abstract). Still, the app crashes in the previews. I found that this only happens in the preview canvas, works fine in the simulator and on my iPhone. I am currently using the latest Xcode build, but I had the same issue in Xcode 13.
Any ideas why this is happening?

Read json-data from url, but it would not viewed

I have a api that give me the follong response:
[{
"id": 1,
"title": "Learn Grinding"
}, {
"id": 2,
"title": "See the messure".
}]
and in my view I like to view this in a list. Later I like to save it into Core Data. But for testing, i just like to see the values in a list. But there is nothing to see :(
The list is empty. With the same content I try to use the Apple-Example with the itunes-List and this work in this ViewController.
With the first Button I test, if I can add a value to the database, and this works fine. Only the List of the json-data would not be read and viewed.
import SwiftUI
struct Response: Codable {
var results: [Result]
}
struct Result: Codable {
var id: Int
var title: String
}
struct TutorialsView: View {
#StateObject var viewRouter: ViewRouter
#State private var results = [Result]()
#Environment(\.managedObjectContext) var managedObjectContext
#FetchRequest(
entity: Tutorials.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Tutorials.title, ascending: true)]
) var tutorials: FetchedResults<Tutorials>
var body: some View {
VStack {
Text("Tutorials")
.bold()
Button(action: {
let tutorial = Tutorials(context: managedObjectContext)
tutorial.title = "Describe how to messure"
PersistenceController.shared.save()
}, label: {
Text("Add Tutorial")
})
List {
ForEach(tutorials, id:\.self) { tutorial in
Text("\(tutorial.title ?? "Unknown")")
}
}
List(results, id: \.id) { item in
VStack(alignment: .leading) {
Text(item.title)
.font(.headline)
}
}
.task {
await loadData()
}
}
}
func loadData() async {
guard let url = URL(string: "https://example.org") else {
print("Invalid URL")
return
}
do {
let (data, _) = try await URLSession.shared.data(from: url)
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
results = decodedResponse.results
}
} catch {
print("Invalid data")
}
}
}
struct TutorialsView_Previews: PreviewProvider {
static var previews: some View {
TutorialsView(viewRouter: ViewRouter())
}
}
When I change the url from the itunes to my own, I got this error in the console:
2022-02-17 14:36:19.868821+0100 GrindingCalculator[2460:27599] [boringssl]
boringssl_metrics_log_metric_block_invoke(151) Failed to log metrics
I also try to use a iPhone and install it on this device and there also would be nothing viewed.
Can you see, where my mistake is?

JSON with SwiftUI using Array

I am new to SwiftUI and only used UIKit before. I tried to use JSON to show a title but all tutorial videos work with lists. I dont want to use any list with JSON which shows all data. Only want to fetch for example the second or a specific array for title.
How can I remove the list in SwiftUI?
My View:
struct ContentView: View {
#ObservedObject var networkManager = NetworkManager()
var body: some View {
NavigationView {
List(networkManager.posts) { post in
HStack {
Text(String(post.points))
Text(post.title)
}}
.navigationBarTitle("H4X0R NEWS")
}
.onAppear {
self.networkManager.fetchData()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
NetworkManager:
class NetworkManager: ObservableObject {
#Published var posts = [Post]()
func fetchData() {
if let url = URL(string: "https://hn.algolia.com/api/v1/search?tags=front_page") {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error == nil {
let decoder = JSONDecoder()
if let safeData = data {
do {
let results = try decoder.decode(Results.self, from: safeData)
DispatchQueue.main.async {
self.posts = results.hits
}
} catch {
print(error)
}
}
}
}
task.resume()
}
}
}
And my struct files for Json:
struct Results: Decodable {
let hits: [Post]
}
struct Post: Decodable, Identifiable {
var id: String {
return objectID
}
let objectID: String
let points: Int
let title: String
}
I dont want to use any list with JSON which shows all data. Only want
to fetch for example the second or a specific array for title.
You can use a computed property to access the specific element (and its title) from the posts array:
struct ContentView: View {
#ObservedObject var networkManager = NetworkManager()
// return the title of the second item in the `posts` array
var title: String {
guard networkManager.posts.count >= 2 else {
// decide what to do when data is not yet loaded or count is <= 1
return "Loading..."
}
return networkManager.posts[1].title
}
var body: some View {
NavigationView {
Text(title)
.navigationBarTitle("H4X0R NEWS")
}
.onAppear {
self.networkManager.fetchData()
}
}
}

SwiftUI - Not able to render the jsonData

I am very new to SwiftUi and I am trying to view the json data and I am currently working on retreiving the weather data from the openweathermap.org which is a free api to retrieve current weather. I am getting Error parsing Weather Json message. I am not sure what I am doing wrong!! Any help would be greatly appreciated and I have been stuck on this for a day. I referred many blogs and tutorials on how to use the Published var and ObservableObject I am not able to fix the problem.
This is my swift file
struct WeatherData {
public var Id: Int
public var main: String
public var weather: [Weather]
public var icon: String
}
extension WeatherData: Decodable, Identifiable {
var id: Int {return Id}
}
struct WeatherView: View {
#ObservedObject var fetch = FetchWeather()
var body: some View {
VStack {
List(fetch.weatherData) {
wthr in
VStack(alignment: .leading){
Text("\(wthr.id)")
Text("\(wthr.weather[0].description)")
Text("\(wthr.icon)")
.font(.system(size:11))
.foregroundColor(Color.gray)
}
}
}
}
}
struct Weather: Decodable {
let description: String
}
struct WeatherView_Previews: PreviewProvider {
static var previews: some View {
WeatherView()
}
}
class FetchWeather: ObservableObject {
#Published var weatherData = [WeatherData] ()
init() {
load()
}
func load() {
let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=London&appid=myapikey")!
URLSession.shared.dataTask(with: url) {
(data, response, error) in
do {
if let wthData = data {
let decodedData = try JSONDecoder().decode([WeatherData].self, from: wthData)
DispatchQueue.main.sync {
self.weatherData = decodedData
}
}
else {
print("No json Data available")
}
}catch {
print("Error parsing Weather Json")
}
}.resume()
}
}
Try this code. I have signed up to get the api and corrected the Model, ViewModel and View accordingly. I have not added the image loader for icon strings.
import SwiftUI
struct Weather: Decodable{
var description: String
var icon :String
}
struct MainData: Decodable {
var temp: Double
var pressure: Int
var humidity: Int
var temp_min: Double
var temp_max: Double
}
struct WeatherData: Decodable, Identifiable {
var id: Int
var main: MainData
var weather: [Weather]
var name: String
}
struct WeatherView: View {
#ObservedObject var fetch = FetchWeather()
var body: some View {
VStack(alignment: .leading) {
Text("Current Weather").font(.title).padding()
List(fetch.weatherData) { wthr in
HStack {
VStack(alignment: .leading){
Text("\(wthr.name)")
Text("\(wthr.weather[0].description)")
.font(.system(size:11))
.foregroundColor(Color.gray)
}
Spacer()
VStack(alignment: .trailing){
Text("\(wthr.main.temp-273.15, specifier: "%.1f") ÂșC")
}
Text("\(wthr.weather[0].icon)") // Image from "https://openweathermap.org/img/w/\(wthr.weather[0].icon).png"
.foregroundColor(Color.gray)
}
}
}
}
}
class FetchWeather: ObservableObject {
#Published var weatherData = [WeatherData]()
private let baseURL = "https://api.openweathermap.org/data/2.5/weather?q="
private let cities = [ "London", "Mumbai", "New+york", "Vatican+City" ]
private let api = "&appid="+"e44ebeb18c332fff46ab956bb38f9e07"
init() {
for city in self.cities {
self.load(self.baseURL+city+self.api)
}
}
func load(_ urlString: String) {
if let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
do {
if let wthData = data {
let decodedData = try JSONDecoder().decode(WeatherData.self, from: wthData)
DispatchQueue.main.sync {
self.weatherData.append(decodedData)
}
}
else {
print("No json Data available")
}
} catch let error as NSError{
print(error.localizedDescription)
}
}.resume()
} else {
print("Unable to decode URL")
}
}
}