swift-sunrise-sunset

0.2.0

A package for getting the sunrise or sunset for a given location and time in Swift.
natesabrown/swift-sunrise-sunset

What's New

0.2.0

2024-06-14T00:10:06Z

The most significant change in this release is the argument label for date for sunrise and sunset functions has been changed from on to for. So usage goes from sunrise(on:... to sunrise(for:... which reads better for dates like .now and "tomorrow".

What's Changed

New Contributors

Full Changelog: 0.1.0...0.2.0

Logo showing the Sun rising over a mountain with birds flying in the foreground

Swift Sunrise/Sunset

Extensible and lightweight package for getting the sunrise and sunset for a location and time in Swift.

Motivation

Getting the sunrise or sunset is useful for many creative and practical applications.

Ideally developers would use a first-party solution. Apple's WeatherKit offers sunrise and sunset times, but Apple developers only get 500,000 calls for free per month. Thankfully, we can calculate the sunrise or sunset for a given location and time using an on-device algorithm.

This package is designed with the following principles at its core:

  • Extensibility: Folks have developed different algorithms for calculating sunrise and sunset times, with varying results. This package provides an easy way to add additional algorithms through the SunriseSunsetProvider type.

  • Modernity: This package follows the latest Swift style and is distributed through Swift Package Manager.

  • Test Coverage: Unit tests verify that provided methods work as expected, so you can feel more comfortable pulling this code in than a snippet.

Usage

To get the sunrise, use the SwiftSunriseSunset.sunrise(...) method:

let sunrise: Date? = SwiftSunriseSunset.sunrise(
    for: Date.now,
    in: TimeZone.current,
    at: CLLocationCoordinate2D(
        latitude: 37.773972, 
        longitude: -122.431297
    )
)

Usage is identical for the SwiftSunriseSunset.sunset(...) method.

Both methods have overloads to explicitly pass the latitude and longitude, so it is not necessary to import CoreLocation to use this package.

Credits

Thanks goes to Paul Schlyter, who released a C algorithm for calculating sun times to the public domain in 1992. The primary algorithm for sun times calculations is derived from his original code.

This was inspired by the work of Neil Tiffin (GitHub: neilt) who in 2019 ported Schlyter's sun times algorithm to Swift and published as a gist.

License

This package is released under the MIT license. See LICENSE for details.

Description

  • Swift Tools 5.9.0
View More Packages from this Author

Dependencies

Last updated: Sat Oct 19 2024 08:17:16 GMT-0900 (Hawaii-Aleutian Daylight Time)