dwyl / learn-apple-watch-development

:green_book: Learn how to build Native Apple Watch (+iPhone) apps from scratch!
55 stars 5 forks source link

HTTP Request - GET/POST displayed in a view #37

Open sohilpandya opened 7 years ago

sohilpandya commented 7 years ago

Now that we have been able to make a get request on a playground #34, we will move on to make this information show up on a view alongside making it possible to make a post request.

We will be using httpbin for making the HTTP requests.

I'll write up a process as I go along creating this demo app.

sohilpandya commented 7 years ago

I'm using https://github.com/typicode/json-server to create a local api which I can send get/post requests to.

I've set the db in a db.json file

{
  "ios" : {
      "project_name":"iOS",
      "total_time":0,
      "color":"blue"
  },
  "elm": {
      "project_name": "elm",
      "total_time":0,
      "color":"blue"
  }
}
sohilpandya commented 7 years ago

I'm using json-server to create a simple db.json file that contains the following information:

{
  "store": [{
    "id": 0,
    "ios": {
      "project_name": "iOS",
      "total_time": 0,
      "color": "blue"
    }
  },{
    "id": 1,
    "elm": {
      "project_name": "elm",
      "total_time": 0,
      "color": "blue"
    }
  }]
}

Currently using localhost:3000 for getting and posting information

sohilpandya commented 7 years ago

OK, so I've posted a question related to convering dictionaries to json here - https://stackoverflow.com/questions/44368070/dictionary-to-json-being-serialised-twice-in-swift-3

I can't seem to get it to post correctly, the format it appears in is incorrect as you can see in the code below

{
  "store": [
    {
      "id": 0,
      "ios": {
        "project_name": "iOS",
        "total_time": 0,
        "color": "blue"
      }
    },
    {
      "id": 1,
      "elm": {
        "project_name": "elm",
        "total_time": 0,
        "color": "blue"
      }
    },
    {
      "{\"newTask\":{\"project_name\":\"iOS\",\"total_time\":0,\"color\":\"blue\"}}": "",
      "id": 2
    }
  ]
}
sohilpandya commented 7 years ago

@iteles could see that I was getting a bit deflated today because of this issue but someone has answered the question in Stack Overflow! 🎉 Can continue the work rather than putting it to the side!

sohilpandya commented 7 years ago

We are now able make the POST request!

turns out we needed to specify that the context was in json using the following line: request.setValue("application/json", forHTTPHeaderField: "Content-Type")