0

I have the following classes that perform a network call -

import SwiftUI
import Combine

struct CoinsView: View {
    
    private let coinsViewModel = CoinViewModel()
    
    var body: some View {
        Text("CoinsView").onAppear {
            self.coinsViewModel.fetchCoins()
        }
    }
    
}

class CoinViewModel: ObservableObject {
    
    private let networkService = NetworkService()
    
    @Published var data = String()
    
    var cancellable : AnyCancellable?
    
    func fetchCoins() {
        cancellable = networkService.fetchCoins().sink(receiveCompletion: { _ in
            print("inside receive completion")
        }, receiveValue: { value in
            print("received value - \(value)")
        })
    }
}

class NetworkService: ObservableObject {
    
    
    private var urlComponents : URLComponents {
        var components = URLComponents()
        components.scheme = "https"
        components.host = "jsonplaceholder.typicode.com"
        components.path = "/users"
        return components
    }
    
    var cancelablle : AnyCancellable?
    
    func fetchCoins() -> AnyPublisher<Any, URLError> {
        return URLSession.shared.dataTaskPublisher(for: urlComponents.url!)
            .map{ $0.data }
            .receive(on: DispatchQueue.main)
            .eraseToAnyPublisher()
    }
}

What I want to achieve currently is just to print the JSON result.

This doesn't seem to work, and from debugging it never seems to go inside the sink{} method, therefor not executing it.

What am I missing?


After further investigation with Asperi's help I took the code to a clean project and saw that I have initialized a struct that wraps NSPersistentContainer which causes for some reason my network requests not to work. Here is the code, hopefully someone can explain why it prevented my networking to execute -


import SwiftUI

@main
struct BasicApplication: App {
    
    let persistenceController = BasicApplciationDatabase.instance
    
    @Environment(\.scenePhase)
    var scenePhase
    
    
    var body: some Scene {
        WindowGroup {
            CoinsView()
        }
        .onChange(of: scenePhase) { newScenePhase in
            switch newScenePhase {

                case .background:
                    print("Scene is background")
                    persistenceController.save()
                case .inactive:
                    print("Scene is inactive")
                case .active:
                    print("Scene is active")
                @unknown default:
                    print("Scene is unknown default")
            }
        }
    }
}

import CoreData

struct BasicApplciationDatabase {
    
    static let instance = BasicApplciationDatabase()
    
    let container : NSPersistentContainer
    
    init() {
        container = NSPersistentContainer(name: "CoreDataDatabase")
        container.loadPersistentStores { NSEntityDescription, error in
            if let error = error {
                fatalError("Error: \(error.localizedDescription)")
            }
        }
    }
    
    func save(completion : @escaping(Error?) -> () = {_ in} ){
        let context = container.viewContext
        if context.hasChanges {
            do {
                try context.save()
                completion(nil)
            } catch {
                completion(error)
            }
        }
    }
    
    func delete(_ object: NSManagedObject, completion : @escaping(Error?) -> () = {_ in} ) {
        let context = container.viewContext
        context.delete(object)
        save(completion: completion)
    }
}
Machavity
  • 30,841
  • 27
  • 92
  • 100
Alon Shlider
  • 1,187
  • 1
  • 16
  • 46
  • Works fine here with just copy/paste. Xcode 13.3 / iOS 15.4. Look for other places: project/network/env configuration. – Asperi Apr 16 '22 at 16:35
  • @Asperi any extra information I can provide so you can help me? I am kinda clueless – Alon Shlider Apr 16 '22 at 16:59
  • @Asperi I know that in the past you needed to provide internet permissions to your app, is it something that is needed today? and I am using the same versions as you are – Alon Shlider Apr 16 '22 at 17:01

0 Answers0