Danny의 iOS 컨닝페이퍼
article thumbnail
Published 2022. 12. 24. 02:36
[iOS/Swift] WeatherKit 사용법 Xcode/Framework
반응형

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가 날씨의 데이터를 얻어오기 위한인터페이스
    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 사용
    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 파일 생성하기

npm 생성

 

이름을 정해준다 (weatherappserver)

 

설치 기다린 후 Yes

 

2. index를 app으로 변경

  • 위에서 생성된 JSON 파일 수정 및 터미널에서 추가

  • 위의 작업을 마치면 아까 위에서 다운로드한 키(Key) 파일을 WeatherAppServer 폴더에 넣기

 

3. app.js 세팅

  • 생성된 app.js 파일로 들어가 아래코드와 같이 작성해 준다
    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 터미널을 이용하여 작업

// 형식
{
"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 값 생성됨
// 형식 (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

// 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

 

 

 

반응형
profile

Danny의 iOS 컨닝페이퍼

@Danny's iOS

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!