skip to Main Content

I have been using Youtube to help me with learning how to use API and converting to JSON using SwiftUI. This is my first time actually using it and could use help, if possible please… this Is what my code is showing: "can not find error in scope"

This is the code so far:

import SwiftUI

class ViewModel: ObservableObject{
    
    func fetch() {
        guard let url = URL(string: "http://www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata") else {
            
            return
        }
        
    }
    let task = URLSession.shared.dataTask(with: url) { data;
        error; in
        guard let data = data, error == nil else {
            return
        }
         // Convert to JSON
        
        
    }
}

I am so sorry, I am still very new to this all.

Thank you!

I have tried using Youtube for help.

2

Answers


  1. There are two (actually three) serious mistakes.

    • The closing brace above let task is wrong, it must be at the end.
    • The closure of dataTask has three parameters separated by comma

    And it’s good practice to handle/print the error. If there is no error data has a value and can be forced unwrapped.

    class ViewModel: ObservableObject {
        
        func fetch() {
            guard let url = URL(string: "http://www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata") else {
                return
            }
            
            let task = URLSession.shared.dataTask(with: url) { data, response, error in
                if let error {
                    print(error)
                    return
                }
                
                // Convert to JSON
                // It's guaranteed that data has a value
                
            }
        }
    }
    

    Side note:

    Rather than YouTube where anybody can publish anything read/watch serious tutorials like Hacking With Swift.

    Login or Signup to reply.
  2. This may help you.

    import SwiftUI
    
    class ViewModel: ObservableObject {
        
        func fetch() {
            guard let url = URL(string: "http://www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata") else {
                return
            }
            
            let task = URLSession.shared.dataTask(with: url) { data, response, error in
                guard let data = data, error == nil else {
                    return
                }
                
                // Convert to JSON
                do {
                    let json = try JSONSerialization.jsonObject(with: data, options: [])
                    // Process the JSON data
                    
                } catch {
                    // Handle JSON parsing error
                }
            }
            
            task.resume()
        }
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search