WeatherKit

RSS for tag

Bring 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

66 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Consistently getting JWT errors
I have added the WeatherKit capability and enabled it in the developer account for the respective app id. I continually get this error. Any ideas on how to fix this? Failed to generate jwt token for: com.apple.weatherkit.authservice with error: Error Domain=WeatherDaemon.WDSJWTAuthenticatorServiceListener.Errors
4
3
1.4k
Mar ’24
WeatherKit Historical Data Availability
Hello, Our team is leveraging WeatherKit for our product, with requirements to obtain historical, current, and forecasted weather data. Our research indicates that WeatherKit supports all these needs, albeit with a caveat regarding historical data. According to this discussion on the developer forums, historical data should be available post-August 2021. However, we've encountered issues accessing historical data for certain locations beyond this date. Are these gaps in data availability a known issue within WeatherKit's service? If so, could you provide any insights into when we might expect a resolution? Thank you for your assistance.
1
1
505
Mar ’24
WeatherKit always returns 404 at specific lat/lon within US
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?
9
2
792
Feb ’24
Historical weather from WeatherKit and Date confusion
I've tried to find the solution to my issue on this forum and general web searches. I see a lot of similar issues but no clear advice how to answer. I have some fairly simple code to get a .daily historical weather object as below: var gameLocation: CLLocation = CLLocation() switch game.country { case .us: gameLocation = CLLocation(latitude: homeTeam.sFactors.gpsCoord.lat, longitude: homeTeam.sFactors.gpsCoord.long) case .germany: gameLocation = CLLocation(latitude: GameCountry.germany.gpsCoord.lat, longitude: GameCountry.germany.gpsCoord.long) case .uk: gameLocation = CLLocation(latitude: GameCountry.uk.gpsCoord.lat, longitude: GameCountry.uk.gpsCoord.long) case .mexico: gameLocation = CLLocation(latitude: GameCountry.mexico.gpsCoord.lat, longitude: GameCountry.mexico.gpsCoord.long) } var gameStartDate: Date = Date() do { gameStartDate = try DateRelatedHelpers().convertISO8601StringToDate(from: game.date) print("Date string: \(game.date), Date: \(gameStartDate)") } catch { throw DateHelperError.invalidDateString } let gameEndDate = Calendar.current.date(byAdding: .day, value: 1, to: gameStartDate)! let gameWeather = try! await weatherService.weather(for: gameLocation, including: .daily(startDate: gameStartDate, endDate: gameEndDate)) I call the function from a loop which is going through several different locations to fetch. I get some valid responses then I receive the following error: Received invalid http response code 404 for request: C2A50990-2E03-497B-BC48-EF7560524E00 Encountered an error when fetching weather data subset; location=<+39.27745100,-76.62297400> +/- 0.00m (speed -1.00 mps / course -1.00) @ 1/24/24, 8:32:28 PM Central Standard Time, error=responseFailed: 404 WeatherDaemon.WDSClient<WeatherDaemon.WeatherResource>.Errors.responseFailed(<NSHTTPURLResponse: 0x6000003d5dc0> { URL: https://weather-data.apple.com/v3/weather/en-US/39.277/-76.623?timezone=America/New_York&dataSets=forecastDaily&dailyStart=2023-09-10T17:00:00Z&dailyEnd=2023-09-11T17:00:00Z&country=US&deviceLanguages=en-US&clientMetadata=CgJVUxoFZW4tVVNKAFABWBRgA4ABA5gBALoBAhAB4gEICgseHR8hICLyAQJVUw } { Status Code: 404, Headers { "Access-Control-Allow-Origin" = ( "*" ); "Cache-Control" = ( "max-age=0, no-cache, no-store" ); Connection = ( "keep-alive" ); "Content-Length" = ( 0 ); "Content-Security-Policy" = ( "default-src 'self';" ); Date = ( "Thu, 25 Jan 2024 02:32:29 GMT" ); Expires = ( "Thu, 25 Jan 2024 02:32:29 GMT" ); Pragma = ( "no-cache" ); Server = ( Apple ); "Strict-Transport-Security" = ( "max-age=31536000; includeSubdomains" ); "X-Apple-Origin" = ( "f6fe362e-be7c-35f4-b131-3b1f903b4bca" ); "X-Cache" = ( "TCP_MISS from a184-28-40-133.deploy.akamaitechnologies.com (AkamaiGHost/11.4.0-53477943) (-)" ); "X-Content-Type-Options" = ( nosniff ); "X-Frame-Options" = ( SAMEORIGIN ); "X-REQUEST-ID" = ( "C2A50990-2E03-497B-BC48-EF7560524E00" ); "X-XSS-Protection" = ( "1; mode=block" ); } }, Optional("")) I also get this warning on any call that receives data: Aborting silent interpolation: additional missing products that need to be fetched from the server anyway; location=CLLocationCoordinate2D(latitude: 39.277451, longitude: -76.622974), missing products=[WeatherDaemon.WeatherProduct.forecastDaily] My dates are in UTC time. I assume the calls return data in the local time of the location. Could this be an issue with Dates (i.e. local vs location date)? Any assistance would be appreciated.
1
0
407
Jan ’24
Need strategy for using WeatherKit in the background
I asked a similar question a while back: https://developer.apple.com/forums/thread/730946 Since then I have a new Mac and new iPhone and so I now have the hardware to actually play with WeatherKit. I've worked my way past all the entitlements stuff and have been able to use and expand on online examples. Cool. Trouble is, nearly every example you can find uses code designed to update the UI as fresh weather data is fetched. My app currently uses background URL fetches to obtain weather data, make some calculations and take appropriate actions, all in the background. Updating the UI was a separate challenge. So which asynchronous tool is the right one for this? How can I quickly update my existing code to call WeatherKit instead of going to a weather site for a download? I currently use something like a download task session: let weatherTask = session.downloadTask (with: URL(string: urlString)!) weatherTask.taskDescription = "weather" weatherTask.resume() or a dataTask session: var request = URLRequest(url: url) request.httpMethod = "GET" request.addValue("text/html", forHTTPHeaderField: "Content-Type") let taskWeatherPOP = URLSession.shared.dataTask(with: request) { (data, response, error) in if error != nil { print("Error is \(String(describing: error))") } if let POPData = data, let report = String(data: POPData, encoding: String.Encoding.utf8) { if weatherReportPOP.contains("ServiceUnavailable") { print("A Weather POP report error") } else { weatherReportPOP = report } // Close the IF service unavailable } // Closes the IF weather data is not nil } // Close Task Weather taskWeatherPOP.resume()
1
0
557
Jan ’24
How Come My WeatherKit Sample App Doesn't Work?
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.
2
1
878
Jan ’24
WeatherKit localization options
I am working on an app that pulls data from weatherKit, including the conditionCode property, the content of which is displayed to the user. I wish to localize the data pulled from weatherKit but when pulling data from: weatherkit.apple.com/api/v1/weather/de/{latitude}/{longitude} The conditionCode and other strings is in english. Same is true if the language parameter is set to es, ja or something else. Am I doing something wrong or is localization yet to be supported in weatherKit? I can't find any documentation on this.
4
0
2.7k
Jan ’24
Syntax for getting precipitationChance?
I'm getting my feet wet with weatherKit and have managed to get all the current weather I need with the code below. My app requires one more thing - the chance of precipitation in the next 0-20 minutes or so - in order to close the windows if the odds exceed some threshold. I haven't been able to find a single code example of retrieving the forecasted rain odds. It looks like the number I need will be in the MinuteWeather contained? in the HourlyForecast but it's completely a mystery to me how to extract what I need. I need a trail of breadcrumbs! I tried getting the hourly and daily forecasts but the value I'm looking for isn't there. import Foundation import WeatherKit @Observable class WeatherManager { private let weatherService = WeatherService() var weather: Weather? func getWeather(lat: Double, long: Double) async { do { weather = try await Task.detached(priority: .userInitiated) { [weak self] in return try await self?.weatherService.weather(for: .init(latitude: lat, longitude: long)) }.value } catch { print("Failed to get weather data. \(error)") } print("\(weather)") do { let daily = try await weatherService.weather(for: .init(latitude: lat, longitude: long), including: .daily) let hourly = try await weatherService.weather(for: .init(latitude: lat, longitude: long), including: .hourly) print("Daily: \(daily)") print("Hourly: \(hourly)") } catch let error { print("Failed to get the forecast. \(error)") } } // close getWeather function var icon: String { guard let iconName = weather?.currentWeather.symbolName else { return "--" } return iconName } var temperature: String { guard let temp = weather?.currentWeather.temperature else { return "--" } let convert = temp.converted(to: .fahrenheit).value return String(Int(convert)) + "°F" } var humidity: String { guard let humidity = weather?.currentWeather.humidity else { return "--" } let computedHumidity = humidity * 100 return String(Int(computedHumidity)) + "%" } var pressure: String { guard let press = weather?.currentWeather.pressure else { return "--" } let convertP = press.converted(to: UnitPressure.inchesOfMercury).value return String((convertP)) + " in. Hg" } var UVindex: String { guard let uv = weather?.currentWeather.uvIndex.value else { return "--" } return "\(uv)" + " index" } var POP: String { ???? return String(Int(chance)) + "%" } }
1
0
478
Jan ’24
Does WeatherKit Historical Request work in every country?
Hi! My app, Temp Blanket, uses WeatherKit to provide users with historical high and low temperatures (as well as some weather condition info) for the location from which they wish to request data - they enter the location in a textfield that I then convert to Geo Coordinates before passing on to WeatherKit. A user in Germany has informed me that her results for Dresden do not match the actual temperatures in the last few days. Actual temperates have been in the -13 to 2 C range and she is seeing a range of 4 to 21 C. In fact, she reports that she gets the same temperatures, no matter what location she tries. When I try Dresden in my app (from my office in Fort Lauderdale, FL) I get correct temperatures for Dresden. Another data point - If I try to get temperatures for Nairobi, Kenya for the last few days, I get the correct temperatures for yesterday (High of 22C, Low of 16C) but the prior days' temps are very far off. I get temps in the range of -12 to 1 C but the actual temps were 15 to 26 C. The temperature history data seems to work correctly in the UK, based on feedback from a user there. So, I have to wonder and ask - does WeatherKit historical data work correctly for all locations worldwide or is it not reliable in certain locations/countries? This is critical information to have so that we do not have dissatisfied users in countries where this service is not yet working correctly. I would disable the app in those countries if this were the case but I need to know what those countries are. Thanks in advance.
1
0
397
Jan ’24
Apple Weatherkit API is returning 404 trying to query for historical hourly forecasts
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!
0
1
392
Jan ’24
Apple Weather Kit - Why do past hourly forecast values change?
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
1
0
371
Jan ’24
Intermittent 404 Not Found responses
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?
10
3
1.2k
Jan ’24
WeatherKit 404s
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?
0
0
341
Jan ’24
WeatherKit Gives 404
When I'm using the following code into the simulator it gives the wanted result: Button {                 Task {                     localWeather = try await WeatherService.shared.weather(for: CLLocation(latitude: 52.5153, longitude: 6.08565), including:  .daily(startDate: Date(), endDate: Calendar.current.date(byAdding: .day, value: 1, to: Date())!)).first.debugDescription                 }             } label: {                 Text("Get the test weather")             }             Text(localWeather) When I'm using this exact code on a real device I get the following 404 error: [WeatherDataService] Received invalid http response code 404 for request: C7AEC7CC-E5F7-425D-8491-25B9302E2A0F:0 [WeatherService] Encountered an error when fetching weather data subset; location=<+52.51530000,+6.08565000> +/- 0.00m (speed -1.00 mps / course -1.00) @ 05/01/2023, 13:55:53 Central European Standard Time,  error=responseFailed(<NSHTTPURLResponse: 0x282ce0260> { URL: https://weather-data.apple.com/v3/weather/en/52.515/6.086?timezone=Europe/Amsterdam&dataSets=forecastHourly,forecastDaily&dailyStart=2023-01-10T12:00:00Z&dailyEnd=2023-01-10T12:00:00Z&hourlyStart=2023-01-10T11:00:00Z&hourlyEnd=2023-01-10T16:00:00Z&country=NL } { Status Code: 404, Headers {     "Access-Control-Allow-Origin" =     (         "*"     );     "Cache-Control" =     (         "max-age=0, no-cache, no-store"     );     Connection =     (         "keep-alive"     );     "Content-Length" =     (         0     );     "Content-Security-Policy" =     (         "default-src 'self';"     );     Date =     (         "Thu, 05 Jan 2023 12:59:27 GMT"     );     Expires =     (         "Thu, 05 Jan 2023 12:59:27 GMT"     );     Pragma =     (         "no-cache"     );     Server =     (         "AppleHttpServer/21be5247c6351682d1d9aa22fe98c8f0d4902838"     );     "Strict-Transport-Security" =     (         "max-age=31536000; includeSubDomains",         "max-age=31536000"     );     "X-Apple-Origin" =     (         "bcd49c7f-c567-3921-a041-3d4ef58e5423"     );     "X-B3-TraceId" =     (         c8c6547722afc53f     );     "X-Cache" =     (         "TCP_MISS from a104-110-190-91.deploy.akamaitechnologies.com (AkamaiGHost/10.10.3-45298580) (-)"     );     "X-Content-Type-Options" =     (         nosniff     );     "X-Frame-Options" =     (         DENY     );     "X-REQUEST-ID" =     (         "407e37bc-ddf6-45fd-84d0-1d3d3b8651b0"     );     "X-XSS-Protection" =     (         "1; mode=block"     ); } }, Optional("")) I fixed it once by deleting Xcode and the app from my iPhone, but that doesn't work anymore. Any suggestions?
3
3
1.4k
Dec ’23
WeatherKit returning incorrect dates for Forecast
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
0
0
343
Dec ’23
WeatherKit REST API parameter validation inconsistency
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...
1
0
357
Dec ’23
WeatherKit: Couldn't lookup symbols
I'm not able to inspect WeatherKit objects like HourWeather and CurrentWeather using the Xcode debugger and breakpoints. When I pause on a breakpoint and try something like po hours where hours is a [HourWeather] I get a debugger error like Couldn't lookup symbols: type metadata accessor for WeatherKit.HourWeather. Is there something about WeatherKit that prevents the debugger from printing out its objects?
1
1
642
Nov ’23
WeatherKit symbol for single location.
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?
0
0
388
Nov ’23
WeatherKit REST API Invalid Signature (php)
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?
0
0
420
Nov ’23