An iOS Shortcut to Send iPhone Battery Level to a URL

For reasons only related to his mentioning of battery levels and automation in his 2021 Week Eight update, I was prompted by Paul Capewell to see if there was a way to send the current battery level of my iPhone to a URL where I could archive it.

This turned out to be pretty easy; because there’s no simple way to share Shortcuts, here are some screen shots. I created a new Shortcut called Post Battery Level and added the URL where I wanted to send the value (I’ve redacted that URL in the screen shot):

iPhone screen shot showing Shortcut for setting URL

Next I get the battery level (there’s a built-in scripting component for this — search for ”Get battery”), and use the “Get contents of URL” component to HTTP POST the value as a form, with the battery level sent as the “battery” field:

iPhone Shortcut screen shot showing getting the battery level and POSTing it

On the server side, the simplified version of what I do is this, a short PHP script to grab the value and stick it in a MySQL table with a timestamp:

<?php

if ($_POST) {

  $db = new mysqli("localhost", "REDACTED", "REDACTED", "REDACTED");

	$query = sprintf("INSERT into battery (battery_date, battery_level) values ('%s', '%s')",
				strftime("%Y-%m-%d %H:%M:%S"),
				mysqli_real_escape_string($db, $_POST['battery']));

	if (mysqli_query($db, $query) === TRUE) {
		header("HTTP/1.1 201 OK");
	}
}

When I run the Shortcut, a new battery level row gets added to the table:

2021-03-01 17:09:14	82
2021-03-01 17:10:20	82
2021-03-01 17:13:28	82
2021-03-01 17:21:28	82

There’s one stumbling block if I want to run this, say, every 15 minutes: to do that requires either using the Automations tab in Shortcuts to create a new schedule for each time I want the Shortcut to run — 00:00, 00:15, 00:30, etc., 96 in all — or to set up a “repeat” loop in the Shortcut itself, with a 15 minute pause inside the loop, which works, but then renders the Shortcuts app unusable otherwise.

Perhaps in a future version of the Automations setup there were be the “run every X minutes” option that I wished there would be.

In any case, thank you to Paul for the diversion.

Comments

Paul Capewell's picture
Paul Capewell on March 2, 2021 - 12:50 Permalink

Very interesting! As an Android user, I have used various battery life apps in the past which plot, over time, battery usage/depletion, in an attempt to monitor overall use and try and give more accurate predictions. It was always a satisfying blob of data seeing many weeks' worth of data plotted on a scatter diagram which showed variations of charge and use on a daily basis.

(I have since moved to an Android phone which has a battery that lasts 2-3 days of pretty solid use and have stopped using battery logging apps since I now don't need to know if I'm going to make it to the end of the day!)