Harry B
Harry B

Reputation: 61

Unexpected non-void return value in void function swift 4 using json serialisation

I am currently trying to clean up my code on a project by writing a generic function that can be used multiple times. However i need my function to return an array. My error is "Unexpected non-void return value in void function"

Here is my code

func JSONSerialisation(JsonUrl: String) -> NSArray{
    let url = URL(string: JsonUrl)
    let task = URLSession.shared.dataTask(with: url!) { (data, responce, error) in
        if error != nil
        {
            print("error")

        }
        else
        {
            if let content = data
            {
                do
                {
                    if let Json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSArray{
                        return Json //Error occurs here
                    }

                }
                catch
                {

                }

            }

        }

    }
    task.resume()

}

There are a few questions like this on Stack Overflow but so far none of them have been able to fix my problem as they all say add -> NSArray.

Thanks in advance

Upvotes: 2

Views: 627

Answers (1)

AshvinGudaliya
AshvinGudaliya

Reputation: 3314

You can't return data directly from an asynchronous task. Use a closure

Create a Function using a closure like.

func jsonSerialisation(jsonUrl: String, completion block: @escaping ((NSArray) -> ())){
    let url = URL(string: JsonUrl)
    let task = URLSession.shared.dataTask(with: url!) { (data, responce, error) in
        if let e = error{
            print(e.localizedDescription)
        }
        else{
            if let content = data{
                do {
                    if let Json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSArray{
                        block(Json)
                    }
                }
                catch let error{
                    print(error.localizedDescription)
                }
            }
        }
    }
    task.resume()
}

And Call :

jsonSerialisation(jsonUrl: "Your Url") { (json) in
    print(json)
}

This is helpful

Upvotes: 5

Related Questions