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

后端 未结 1 1918
情书的邮戳
情书的邮戳 2021-01-23 16:32

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

相关标签:
1条回答
  • 2021-01-23 16:59

    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

    0 讨论(0)
提交回复
热议问题