Conventions
The rules every API follows
A few rules hold across the whole API. They are said here once, so a page about one API does not have to repeat them. Three outcomes. A lookup that can legitimately find nothing returns null: Storage.get, Cache.get, Keychain.get, Calendar.find, Photos.random. An operation that cannot complete throws, and the error says why: Location.current, file.write, Keychain.set, event.save(). A network request never throws: Http.get and the other verbs return a response whose ok says how it went, with status and error beside it. A Duration or a number of seconds. Anything that takes a length of time (timeout, refreshInterval, staleAfter, expiry, Animation.delay) takes either Duration.minutes(5) or 300. Leading and trailing. Alignment, TextAlign, EdgeInsets.only and CornerRadius.only speak leading and trailing, which flip for right-to-left languages. Values with methods. Color, Font, DateTime, Duration, Distance and Data values carry their own methods: color.opacity(0.5), date.add(Duration.hours(1)), data.toBase64(). What reaches the widget is plain data; the methods live on prototypes and never cross. A Data value's bytes never cross either. It is a handle, { type, mimeType, size, source }, and the bytes stay in the app until something asks for them, so a large file moves between Http, Files and Quick Look at no cost. Asking for permission. isAvailable says whether a thing works in the process the script is in: a widget cannot show an alert, a Mac has no Live Activities. status, isAuthorized and requestAccess() cover what the user has to grant. Location, Calendar, Reminder, Motion, Photos, Contacts and LiveActivity all have them, and requestAccess() works only in the app, since a widget has nowhere to put the permission sheet. Drawing. Whatever draws a shape takes fill, stroke and strokeWidth, as Path does. Whatever rounds takes cornerRadius, a number or a CornerRadius value. Square things (Circle, Gauge, QR codes) take size, or width and height. Text and symbols take color and font.
Examples
The three outcomes
var key = Keychain.get("apiKey"); // null when nothing is stored
if (!key) {
Script.setWidget(new Widget({ child: Text("No API key") }));
}
var res = Http.get(url); // never throws
if (!res.ok) console.warn(res.status, res.error);
var here = Location.current(); // throws when access was deniedTime, either way
Http.get(url, { timeout: Duration.seconds(10) });
Http.get(url, { timeout: 10 });Leading and trailing
Container({
alignment: Alignment.topLeading,
padding: EdgeInsets.only({ leading: 8 }),
cornerRadius: CornerRadius.only({ topTrailing: 12 }),
})Asking first
if (!Calendar.isAuthorized) {
// In the app this shows the sheet; in a widget it throws, so check first.
if (Calendar.requestAccess() !== "authorized") {
Script.setWidget(new Widget({ child: Text("Grant calendar access in the app") }));
}
}