Search code examples
swiftxcodetextviewrest

display the REST API result in textview in Swift doesn't work


I am trying to develop a function to connect and read from a REST API, then display the returning json in a textview, with following code :

func restapiRead()
{
    var request = URLRequest(url: URL(string: "https://reqres.in/api/users?page=1")!)
    request.httpMethod = "GET"

    let session = URLSession.shared
    let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
        print(response!)
        do {
            let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
            print(json)
            self.mytv.text = "\(json as! [[String: AnyObject]])" //> code line 1
            self.mytv.text = "\(json as! NSArray)" //> code line 2
        }
        catch {
            print("error")
        }
    })

    task.resume()    
  }

Actually all code above works without any error, but then I use codeline1 or codeline2 to copy the result in textview, it warns with a "warning" message as :

Cast from '[String : AnyObject]' to unrelated type '[[String : AnyObject]]' always fails

If I run ignore the warning and run, I get the following error at codeline1 (and 2 as well):

Thread 6: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

How can I copy the result as raw json in the textview?

Thank you


Solution

  • you should json convert to string for use textView .

       json.description
    

    tested 100% ok

    code change to :

      func restapiRead()
        {
            var request = URLRequest(url: URL(string: "https://reqres.in/api/users?page=1")!)
            request.httpMethod = "GET"
    
            let session = URLSession.shared
            let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
                print(response!)
                do {
                        let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
    
                     DispatchQueue.main.async {
                    self.mytv.text =  json.description
                       }
                    }
             
                catch {
                    print("error")
                }
            })
    
            task.resume()
          }