반응형
1. Certificates, Identifiers & Profiles 세팅
1. 인증서 클릭
- 애플 디벨로퍼 홈페이지로 들어가서 인증서로 들어가기

2. key 만들기
- 처음으로 키를 생성해줘야 한다.

- 사용할 기능(WeatherKit)에 대해서 체크

- Register 버튼 클릭

- Download 받은 걸 안전한 장소에 보관(한 번만 다운로드 가능하다)
- Key ID와 Apple ID는 만약 Web Token 생성이 필요할 때 사용.


3. App ID 만들기
- Identifiers 클릭
- Continue -> Select Typle : App 클릭

- Bundle ID와 Xcode의 Bundle Identifier랑 같아야 한다




2. Xcode에서 기본 설정
- Capability 클릭

- WeatherKit을 추가해주면 사용 준비 끝

3. 날씨 불러오기
- WeatherService가 날씨의 데이터를 얻어오기 위한인터페이스
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
class MainWeatherViewController { // 모델 private var weatherKit: Weather? func getWeather(location: CLLocation) { Task { do { // WeatherService 싱글턴 사용 let weather = try await WeatherService.shared.weather(for: location) print("Temp: \(weather.currentWeather.temperature)") print("Humidity: \(weather.currentWeather.humidity)") weather.dailyForecast.forEach { dump("\($0.date) High Tmep: \($0.highTemperature)") } } catch { print(String(describing: error)) } } } }
- async/await 사용
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
class MainWeatherViewController { func fetchWeather(location: CLLocation) async throws { do { let weather = try await WeatherService.shared.weather(for: location) print("Temp: \(weather.currentWeather.temperature)") print("Humidity: \(weather.currentWeather.humidity)") weather.dailyForecast.forEach { dump("\($0.date) High Tmep: \($0.highTemperature)") } } catch { print("Error: \(error)") } } }
- 출력 결과

4. 참고
4.1. Node로 Web token 생성하기
순서대로 따라 해보세요
1. JSON 파일 생성하기



2. index를 app으로 변경
- 위에서 생성된 JSON 파일 수정 및 터미널에서 추가






- 위의 작업을 마치면 아까 위에서 다운로드한 키(Key) 파일을 WeatherAppServer 폴더에 넣기
3. app.js 세팅
- 생성된 app.js 파일로 들어가 아래코드와 같이 작성해 준다
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
const express = require("express") const axios = require("axios") const fs = require("fs") const jwt = require("jsonwebtoken") var cors = require("cors") const app = express() const port = 3000 app.use(cors()) app.get("/", async (req, res) => { // This is the key file you downloaded from Apple var privateKey = fs.readFileSync("YOUR KEY FILE FROM DEVELOPER CENTER.p8") // Creating the signed token needs specific data var token = jwt.sign( { sub: "APPID", // the reverse URL App Id you made above, com.github.lucidwild.WeatherApp }, privateKey, { issuer: "TEAMID", // find your TeamID in your developer account expiresIn: "1h", // give it 1 hour of validity keyid: "KEYID", // this is the ID for the key you created algorithm: "ES256", // this is the algorithm Apple used header: { // see details below for this id: "TEAMID.APPID", }, } ) // log your token so you can decode it and manually check it's ok, more below on this console.log(token); const url = "https://weatherkit.apple.com/api/v1/weather/en/51.677612/-2.937941?dataSets=currentWeather&timezone=Europe/London" // add the token to your headers const config = { headers: { Authorization: `Bearer ${token}` }, }; // get the data const { data: weatherData } = await axios.get(url, config) // prove we have data console.log(weatherData.currentWeather) // return the data to your front end res.json(weatherData) }) app.listen(port, () => { console.log(`Server is running on localhost:${port}`) })

- 이와 같이 WebToken과 날씨가 생성된다. Postman에서 Bearer Token 사용하면 된다.

4.2. 수동으로 설정 Web token 생성하기
Base64 Encode and Decode - Online
Encode to Base64 format or decode from it with various advanced options. Our site has an easy to use online tool to convert your data.
www.base64encode.org
1. 위의 홈페이지에서 변환 or 터미널을 이용하여 작업
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 형식 | |
{ | |
"alg": "ES256", | |
"kid": "Key ID", | |
"id": "Team ID.com.github.lucidwild.WeatherApp" | |
} | |
// 터미널에 입력 | |
echo -n '{ "alg": "ES256", "kid": "TV7UW6T69Z", "id": "ZG488AACV6.com.github.lucidwild.WeatherApp" }' | base64 | sed s/\+/-/ | sed -E s/=+$// | |
// Header 값 생성됨 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 형식 (iat: 생성일 ,exp: 만료일) | |
{ | |
"iss": "Team ID", | |
"iat": 1668711342, | |
"exp": 1668714942, | |
"sub": "com.github.lucidwild.WeatherApp" | |
} | |
// 터미널 | |
echo -n '{ "iss": "ZG488AACV6", "iat": "1668678942", "exp": "1668682542", "sub": "com.github.lucidwild.WeatherApp" }' | base64 | sed s/\+/-/ | sed -E s/=+$// | |
// Payload 값 생성됨 |
2. Unixtimestamp converter 사용하여 변환하여 Web Token 얻기
Unix Time Stamp - Epoch Converter
Epoch and unix timestamp converter for developers. Date and time function syntax reference for various programming languages.
www.unixtimestamp.com
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Header.Payload .(콤마)로 연결해 주고 다운받은 키값을(AuthKey_ABC123DEFG.p8) 입력 | |
echo -n "Header.Payload" | openssl dgst -sha256 -binary -sign AuthKey_ABC123DEFG.p8 | openssl enc -base64 | tr -d '\n=' | tr -- '+/' '-_' | |
// Signature 값 생성됨 | |
// 아래 형식으로 (Web token) 완성! | |
Header.Payload.Signature | |
// Postman에서 Bearer Token 값 입력하고 사용하면 된다. | |
// 아래는 Weatherkit 호출 형식 | |
https://weatherkit.apple.com/api/v1/weather/en/51.677612/-2.937941?dataSets=currentWeather&timezone=Europe/London |
반응형
'Xcode > Framework' 카테고리의 다른 글
[iOS/Swift] SceneKit의 사용법 (2) - 주사위 만들기 (0) | 2023.01.08 |
---|---|
[iOS/Swift] SceneKit의 사용법 (1) - 정육면체와 달을 만들어 보자 (0) | 2023.01.07 |
[iOS/Swift] ARKit의 종류 (0) | 2023.01.07 |
[iOS/Swift] CoreML (2) - 훈련 된 Model 사용하기 (3) | 2023.01.04 |
[iOS/Swift] CoreML (1) - Create ML으로 Model 만들기 (0) | 2023.01.03 |