I want to reflect the JSON data that I got from the API created by Django in the actual TableView.

Asked 2 years ago, Updated 2 years ago, 71 views

The URL where the following json data is returned is http://127.0.0.1:8000/api/v1/
I got the response correctly on the simulator, but when I tried it on the actual machine, I couldn't get it. What should I do?
I'm using Alamofire 4.0.

JSON

{
"books": [
{
  "id"—1, 
  "name": "Introduction to Django", 
  "publisher": "GeekLab Nagano", 
  "page"—10, 
  "impressions": [
    {
      "id"—1, 
      "comment": "\r\nI'm sleepy in the middle."
    }, 
    {
      "id"—2, 
      "comment": "Ah"
    }, 
    {
      "id"—3, 
      "comment": "good"
    }
  ]
}, 
{
  "id"—2, 
  "name": "Raspberry Pi Introduction", 
  "publisher": "GeekLab Nagano", 
  "page"—15, 
  "impressions": [ ]
}
]
}

Code

 variableTitle= [String]()
variableDetail=[String]()
let url: String = "http://127.0.0.1:8000/api/v1/"

funcloadData(){
    Alamofire.request(url).responseJSON{
        response in

        guard let value = response.result.value else {
            return
        }
        let json=JSON(value)
        letbooks=json ["books"]

        US>for item in books.arrayValue{
            self.tableTitle.append(item["name"].stringValue)
            self.tableDetail.append(item["publisher"].stringValue)
        }

        print(self.tableTitle)
        print(self.tableDetail)


        self.tableView.reloadData()
    }
}

swift ios json django alamofire

2022-09-30 16:11

1 Answers

The default host for running Django, 127.0.0.1, is accessible only from the machine running Django, so please boot as follows:

 python manage.py runserver 0.0.0.0:8000

You can now access it from other machines on the same network by http://<Django machine name or IP address >:8000/.

Add

I got the response correctly on the simulator, but when I tried it on the actual machine, I couldn't get it. What should I do?

I don't know what the situation is with "Unable to retrieve".
The situation where HTTP requests do not work is

  • Cannot connect to server
  • The server responds, but the HTTP status code shows an error (e.g., 500).
  • Content (JSON data in this case) cannot be retrieved correctly in response from the server

and so on.

Depending on where these things don't work, the cause and the way you deal with them will change.
I don't know Swing, so I don't know exactly how to check it, but I recommend that you check where these things are not working when you communicate with HTTP.

Additional 2

Django's settings.py has settings to specify which hosts are allowed to connect.
Default is

ALLOWED_HOSTS=[]

You can only access it from a machine running Django, so you can access it from anywhere.

ALLOWED_HOSTS=[*]

Let's say


2022-09-30 16:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.