System status shows WeatherKit as available, but currently all calls returns status 401 with the response body containing {"reason": "NOT_ENABLED"}.
We have been running the exact same code in production since March 2023. Nothing changed. The system just started returning errors.
Is that happening for anyone else?
WeatherKit
RSS for tagBring weather information to your apps and services through a wide range of data that can help people stay up to date, safe, and prepared.
Posts under WeatherKit tag
67 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
My app has been using WeatherKit via its REST API for months with success. Suddenly, the weatherkit API only returns to me "reason" : "NOT_ENABLED" now.
I am unsure why it is suddenly telling me WeatherKit is not enabled?
Hi,
We have been using DarkSky's API for a few years now and we've always been able to pull data for at least 3 years prior to the current date.
With WeatherKit, we are seeing that data is only available for the last 2 years. I've seen a few posts confirming this, but I'm curious if we will always be limited to 2 years of data or if this is a temporary situation and as time goes on, WeatherKit will have more and more historical data available? Another way to put it is will Apple always delete any data older than 2 years or will they start to build up an archive so in 10 years from now, they will have 12 total years of data (given they have 2 years right now).
Thanks!
I created my own service to generate a JWT for WeatherKit. When I use this JWT in Postman it works as expected.
However, if I use it in my React application I get a 403 CORS pre-flight check error. What this essentially means is by nature, Safari - before doing the GET call with Authorization header - it does a preflight check OPTIONS call without headers, to check if the service will accept the request. Unfortunately this generates a 403 error instead of an 200, so the GET Call with Authorization header cannot be made.
Is this by design to prevent webfrontends from accessing the API or is this a bug I encountered? Thank you!
This is a app for weather in which i used weatherkit.I have added "privacy - Location when in Usage Description in info of project and also enabled location in features of simulator to Apple.After doing all this ,still the permission message for location is not appearing in app in simulator.Following is my code:
import CoreLocation
import UIKit
//final means this class will not be subclassed
final class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
//to access weather data
let service = WeatherService()
override func viewDidLoad() {
super.viewDidLoad()
setupView()
getUserLocation()
}
func getUserLocation(){
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func getWeather(location : CLLocation){
//asynchoronus task
Task {
do {
//if it throws error
//await tells to wait until function gives results
let result = try await service.weather(for: location)
print("Current : "+String(describing: result.currentWeather))
print("Daily : "+String(describing: result.dailyForecast))
print("Hourly : "+String(describing: result.hourlyForecast))
} catch {
//it will be excecuted
print(error.localizedDescription)
}
}
}
func setupView(){
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else {
return
}
locationManager.stopUpdatingLocation()
getWeather(location: location)
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .denied:
print("location permission denied")
case .authorizedWhenInUse, .authorizedAlways :
manager.startUpdatingLocation()
print("Location Permission Granted")
case .notDetermined :
print("location Permission not determined")
default:
break
}
}
}
Is there a means of accessing historical averages from WeatherKit? I imagine it would be monthly averages.
Apple's Weather app recently introduced "Averages" – both daily and monthly. I'm wondering if this data is derived from WeatherKit. I'm also curious if there exists an API available to developers that hasn't made its way into the documentation yet, or if there are plans for making "averages" available to developers in upcoming improvements to WeatherKit.
Using WeatherKit I want to get a 5-day forecast starting tomorrow,
however, I only get 4 elements in the forecast.
What am I missing here?
public func updateWeather()async{
guard locationManager.location != nil else {locationManager.updateLocation(); return}
if self.needsUpdating{
let startOfToday = Calendar.current.startOfDay(for: Date())
let endOfToday = startOfToday+24*3600
let firstDay:Date = endOfToday+1
let lastDay:Date = firstDay+(5*24*3600)
futureWeather = try? await WeatherService.shared.weather(for: locationManager.location!,
including: .daily(startDate: firstDay, endDate: lastDay)
)
}
}
In my app I retrieve the daily weather for a location via the REST API. This works fine in almost all cases. However, for October 29th (yesterday) it returns a 404 Not Found error. This is an example request that fails:
https://weatherkit.apple.com/api/v1/weather/en/48.1582271841334/11.5418646663957?dataSets=forecastDaily&dailyStart=2023-10-28T22:00:00.0000000Z&dailyEnd=2023-10-29T22:00:00.0000000Z
I have also tried to append the timezone &timezone=Europe/Berlin - but the problem persists.
Maybe it has to do with the fact that Daylight saving time ended yesterday at the location requested (Germany)? It certainly looks like a bug. Where can I report it if this isn't the right place to do so?
When retrieving data using WeatherKit, a CLLocation is passed. What is the range / span of that data? In other words: at what distance to the given location is the returned weather data valid?
I'm trying to make a PHP implementation to fetch data from the WeatherKit REST API.
When using jwt.io to create a JWT, everything works correctly, so my keys, identifiers, etc. are set up correctly.
When using jtw.io to verify my own generated JWT, the header and payload are correct, but "Invalid Signature" is displayed.
The file path for the private key exists and the file is loaded correctly.
My PHP code:
function generate_jwt(): String {
$tmpFilePath = realpath(dirname(__FILE__)).'/';
$filePath = $tmpFilePath.'../AuthKey.pem';
//$filePath = $tmpFilePath.'../AuthKey.p8';
$private_key = NULL;
if (file_exists($filePath)) {
$private_key = file_get_contents($filePath);
}
$header = [
"alg" => "ES256",
"kid" => "XXXXXXXXXX",
"id" => "YYYYYYYYYY.com.thing.stuff",
"typ" => "JWT"
];
$header = $this->base64_url_encode(json_encode($header));
$issuedAt = time();
$payload = [
"iat" => $issuedAt,
"exp" => $issuedAt + 30,
"iss" => "YYYYYYYYYY",
"sub" => "com.thing.stuff"
];
$payload = $this->base64_url_encode(json_encode($payload));
$signature = $this->base64_url_encode(hash_hmac('sha256', "$header.$payload", $private_key, true));
$jwt = "$header.$payload.$signature";
return $jwt;
}
function base64_url_encode($text): String {
return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($text));
}
Any ideas?
Hello, I'm using WeatherKit in a project to display the SF Symbol for the weather in the app toolbar. I have this for the WeatherModel:
import Foundation
import WeatherKit
@MainActor class WeatherManager: ObservableObject {
@Published var weather: Weather?
public func getWeather() async {
do {
weather = try await Task.detached(priority: .userInitiated) {
return try await WeatherService.shared.weather(for: .init(latitude: 28.3772, longitude: -81.5707))
}.value
} catch {
fatalError("\(error)")
}
}
var symbol: String {
weather?.currentWeather.symbolName ?? "xmark.icloud.fill"
}
var temp: String {
let temp =
weather?.currentWeather.temperature
let convert = temp?.converted(to: .fahrenheit).description
return convert ?? ""
}
}
And this in the SwiftUI View:
ToolbarItem(placement: .topBarLeading) {
@ObservedObject var weatherManager = WeatherManager()
Image(systemName: weatherManager.symbol)
.task {
await weatherManager.getWeather()
}
}
But when I build and run the app on my phone it displays the "xmark.icloud.fill" instead of the actual weather.
Did I do something wrong?
I have gone through several tutorials for WeatherKit. But my sample app doesn't return weather data. The following is a list of what I have.
I've registered a Bundle ID for my sample app with the WeatherKit capability on.
I've created a developer profile for my sample app.
I've opened my Xcode project to make sure that the WeatherKit capability is enabled.
I have run my sample app with an actual device.
I have waited for more than 30 minutes for the service to kick in. It's been several days.
The following is my code.
import SwiftUI
import CoreLocation
import WeatherKit
struct ContentView: View {
@State var currentWeather: CurrentWeather?
var body: some View {
NavigationStack {
List {
Group {
SampleCell(title: "Temperature", value: String(currentWeather?.apparentTemperature.value ?? 0.0) + "℃")
SampleCell(title: "Cloud coverage", value: String(currentWeather?.cloudCover ?? 0.0))
SampleCell(title: "Weather condition", value: String(currentWeather?.condition.description ?? ""))
SampleCell(title: "Dew point", value: String(currentWeather?.dewPoint.value ?? 0.0) + "℃")
SampleCell(title: "Humidity", value: String(currentWeather?.humidity ?? 0.0))
SampleCell(title: "Pressure", value: String(currentWeather?.pressure.value ?? 0.0) + "mbar")
SampleCell(title: "Pressure trend", value: String(currentWeather?.pressureTrend.description ?? ""))
SampleCell(title: "Temperature", value: String(currentWeather?.temperature.value ?? 0.0) + "℃")
SampleCell(title: "UV index", value: String(currentWeather?.uvIndex.value ?? 0))
SampleCell(title: "Visibility", value: String(currentWeather?.visibility.value ?? 0.0) + "m")
}
SampleCell(title: "Window direction", value: String(currentWeather?.wind.direction.value ?? 0.0) + "°")
SampleCell(title: "Window speed", value: String(currentWeather?.wind.speed.value ?? 0.0) + "km/h")
SampleCell(title: "Gust", value: String(currentWeather?.wind.gust?.value ?? 0.0) + "km/h")
}
.navigationTitle(Text("CurrentWeather"))
.task {
let service = WeatherService()
let location = CLLocation(
latitude: 35.467081,
longitude: 139.620798
)
do {
let weather = try await service.weather(for: location)
currentWeather = weather.currentWeather
} catch let error {
print(error.localizedDescription)
}
}
}
}
}
struct SampleCell: View {
var title: String
var value: String
var body: some View {
VStack {
HStack {
Text(title)
Spacer()
Text(value)
}
}
}
}
Yet, I constantly get the following warnings.
2023-11-29 09:33:46.504737+0900 WeatherCrazyMama[15279:9734572] [WeatherDataService] Aborting silent interpolation: no interpolator object; location=CLLocationCoordinate2D(latitude: 35.467081, longitude: 139.620798)
2023-11-29 09:33:47.900605+0900 WeatherCrazyMama[15279:9734577] [AuthService] Failed to generate jwt token for: com.apple.weatherkit.authservice with error: Error Domain=WeatherDaemon.WDSJWTAuthenticatorServiceListener.Errors Code=2 "(null)"
2023-11-29 09:33:47.989603+0900 WeatherCrazyMama[15279:9734572] [WeatherService] Encountered an error when fetching weather data subset; location=<+35.46708100,+139.62079800> +/- 0.00m (speed -1.00 mps / course -1.00) @ 2023/11/29 9:33:46 AM Japan Standard Time, error=WeatherDaemon.WDSJWTAuthenticatorServiceListener.Errors 2 Error Domain=WeatherDaemon.WDSJWTAuthenticatorServiceListener.Errors Code=2 "(null)"
The operation couldn’t be completed. (WeatherDaemon.WDSJWTAuthenticatorServiceListener.Errors error 2.)
What am I doing wrong? Thanks.
The status codes returned for REST API queries give a good indication of the issue encountered. Generally:
200 is good
400 means you've passed in bad or incomplete parameters
401 is an authentication issue
However, there's a parameter validation inconsistency on the availability endpoint.
If you pass in out-of-range coordinates to the weather endpoint, you get the expected 400 response code.
But if you pass bad coordinates to the availability endpoint, it blows up and returns a 500 (internal server error).
I've got code that can deal with this response, but it would be much better to know exactly where the problem lies. 500 tells me there's an issue on the server that's out of my control...
For some reason this morning (5 December 2023, ~10:30am UTC) I have been experiencing intermittent WeatherKit API failures with a 404 Not Found status.
There is nothing wrong with the request itself: trying a minute or two later with the exact same request parameters and token returns a successful response.
I can see that it's not a transport issue between me and Apple, as the response I am getting is coming from the Apple servers:
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<center><h1>404 Not Found</h1></center>
<hr>
<center>Apple</center>
</body>
</html>
...and the responding server is AppleHttpServer.
Has anyone else seen this? Is it a regular occurrence, or are they just having a bad day?
For locations in timezones East of me the returned results start at yesterday, Today is Saturday, the results start at Friday. Sometimes results can start 2 gays ago. Locations in my timezone and those west do not behave this way; the results start at Saturday.
I'm doing the most basic request:
self.weather = try await weatherService.weather(for: CLLocation(latitude: location.latitude, longitude: location.longitude) )
My understanding this returns 10-days of forecast.
What is going on?
I need to know if the results are appropriate for the days returned. IE. Is today's forecast for tomorrow, today or yesterday?
Any guidance is appreciated.
Kirk Mahr
I am looking at the forecastHourly data for the same latitude and longitude, from 3 days ago at 00:00 to today at 00:00. I noticed that every hour, around the 15th minute, the reportedTime in the forecastHourly metadata changes:
"readTime": "2023-12-20T07:15:45Z", -> 2023-12-20T07:21:45Z
"reportedTime": "2023-12-20T06:00:00Z", -> 2023-12-20T07:01:18Z
The data for the same time in the past (where the value of forecastStart is the same) is different. What is the reason for this?
"readTime": "2023-12-20T07:15:45Z", -> 2023-12-20T07:21:45Z
"reportedTime": "2023-12-20T06:00:00Z", -> 2023-12-20T07:01:18Z
"forecastStart": "2023-12-18T15:00:00Z", === 2023-12-18T15:00:00Z
"humidity": 0.47, -> 0.46
"temperature": -6.38 -> -6.72
We grid our service area with 6000 points across the US.
There is 1 point in Missouri that fails forecast and anything historical (currentWeather, forecastHourly, and forecastDaily) with a 404 error:
latitude = 37.06089340391355
longitude = -93.00383141966712
This works:
latitude = 37.06089340391355
longitude = -93.006
This does NOT work:
latitude = 37.06089340391355
longitude = -93.005
Even though all of the other points seem to be working, I have lack in trust for this API for returning unexpected results.
Can someone please provide an explanation or resolution?
Yet another day yet another WeatherKit outage it seems.
We have been getting 404s on WeatherKit requests for the past 1.5 days, across a number of different lat/lngs and times. Not all requests are failing and we have confirmed that we are well below our allocated quota per our subscription tier.
Anyone else experiencing similar issues?
WeatherKit has been returning 404 errors for the last four hours without any successful requests. Is anyone else receiving this issue?
Hi,
I am having an issue where I keep getting 404 errors for a particular Lat/Long date combination when trying to fetch historical hourly forecasts. It does not seem to matter if I supply an hourlyEnd value or not. I am always getting a 404 response.
Here is the sample query I am passing to the weatherkit:
https://weatherkit.apple.com/api/v1/weather/en/46.26013/-119.9061?dataSets=forecastHourly&timezone=PST&hourlyStart=2023-08-16T07:00:00Z&hourlyEnd=2023-08-16T15:00:00Z
It seems for some reason nothing is showing up until the end of September when I was doing some tests and changing the dates and times. Is there a limit on how far back the historical can go? Any help would be appreciated! Thank you!