What is REST?
The REST API is an application program interface that uses HTTP request method to transfer data between a client and a server. REST is based on REpresentational State Transfer, the architectural style that underpins the internet.
We use HTTP resource methods for REST. There are a handful of different methods:
• POST - Creates new resources or creates new data. When we creating and sending newer data.
• GET - Gives you the ability to read and receive new data.
• PUT - This method is usually used to updating or replace data that's being sent.
• DELETE - This method is pretty straightforward. This method deletes data.
For this guide we'll be using the "POST" method.
Post Data to Adafruit IO
Since we've previously collected accelerometer data, we'll continue by sending that data to your Adafruit IO feed. In the ViewController.swift file, we'll create a function named postAccelerometerDataX()
.
Then we'll create a constant dictionary and attach our accelerometer data to the dictionary in a string format:
let parameters = ["value": "\(String(format: "%.02f", (motionManager.accelerometerData?.acceleration.x)!))"]
Now we're going to setup the URL request. We'll use a guard let statement so that we can check if the URL we've given is valid:
guard let url = URL(string: "https://io.adafruit.com/api/feeds/your-Feed-Key-Here/data.json?X-AIO-Key=Your-A-IO-Key-Here) else { return }
As you can see, there are placeholders in the URL Endpoint "Your-Feed-Key-Here" and "Your-A-IO-Key-Here".
You'll need to add your Feed Key and Adafruit IO Account Key here. To find your Feed Key, click on the Feeds tab on the left side of the Adafruit IO interface to access your Feeds page:
Once here, look to your right and your feed key should be below the Key column. Copy the key specific to the feed that you'll be using and replace "Your-Feed-Key-Here" with your Feed Key.
Next, to get your Adafruit IO account Key, on your left you should see "View AIO Key". Click on that, and you should see a pop-over menu that displays your Account username and Active Key. The Active Key is your Adafruit IO Key.
Copy the key and replace "Your-A-IO-Key-Here" with your Adafruit IO Key.
Next, we'll create a request variable and give it the value of the URLRequest:
var request = URLRequest(url: url)
Then, we'll give variable request a HTTP POST
method:
request.httpMethod = "POST"
Now, we use the JSONSerialization class to convert JSON into Swift data types like our Dictionary "parameters".
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
This JSONSerialization method, returns a value of type Any and throws an error if the data couldn’t be parsed.
Now we'll pass our request to session.dataTask.
session.dataTask(with: request) { (data, response, error)
This creates a task that sends our contents to a specified URL, then calls a handler upon completion. The completion handler is called when the request is completed. This handler is executed on the delegate queue.
This completion handler takes the following parameters:
• Data - The data returned by the server.
• Response - An object that provides response metadata, such as HTTP headers and status code.
• Error - An error object that indicates why the request failed, or nil
if the request was successful.
The remainder of the function will print in our data in the console or print an error message. Here's the whole function in it's completed form:
func postAccelerometerDataX() { let parameters = ["value": "\(String(format: "%.02f", (motionManager.accelerometerData?.acceleration.x)!))"] guard let url = URL(string: "https://io.adafruit.com/api/feeds/your-Feed-Key-Here/data.json?X-AIO-Key=Your-A-IO-Key-Here) var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return } request.httpBody = httpBody let session = URLSession.shared session.dataTask(with: request) { (data, response, error) in if let response = response { print(response) } if let data = data { do { let json = try JSONSerialization.jsonObject(with: data, options: []) print(json) } catch { print(error) } } }.resume() }
Ok, now we're going to finish up our app.
Page last edited March 08, 2024
Text editor powered by tinymce.