Swift library to access Tesla API based on Tesla JSON API (Unofficial)
Copy Sources
folder into your project
If you don't need any extensions, use this line
pod 'TeslaSwift', '~> 8'
If you need PromiseKit extensions, use this line
pod 'TeslaSwift/PromiseKit', '~> 8'
If you need Combine extensions, use this line
pod 'TeslaSwift/Combine', '~> 8'
If you need Rx extensions, use this line
pod 'TeslaSwift/Rx', '~> 8'
pod 'TeslaSwift/Streaming', '~> 8'
If you need Combine extensions for Streaming, use this line
pod 'TeslaSwift/StreamingCombine', '~> 8'
If you need Rx extensions for Streaming, use this line
pod 'TeslaSwift/StreamingRx', '~> 8'
You can use Swift Package Manager and specify a dependency in Package.swift
by adding this or adding the dependency to Xcode:
.Package(url: "https://github.com/jonasman/TeslaSwift.git", majorVersion: 8)
There are also extensions for Combine TeslaSwiftCombine
, PromiseKit TeslaSwiftPMK
and Rx TeslaSwiftRx
The Streaming extensions are: TeslaSwiftStreaming
, Combine TeslaSwiftStreamingCombine
and Rx TeslaSwiftStreamingRx
Tesla's server is not compatible with ATS so you need to add the following to your app Info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Import the module
import TeslaSwift
Add the extension modules if needed (with the previous line)
import TeslaSwiftPMK
import TeslaSwiftCombine
import TeslaSwiftRx
Perform an authentication with your MyTesla credentials using the web oAuth2 flow with MFA support:
let api = TeslaSwift()
let (webloginViewController, result) = await api.authenticate()
guard let safeWebLoginViewController = authViewControler else { return }
present(safeWebLoginViewController, animated: true, completion: nil)
Task { @MainActor in
do {
_ = try await result()
self.messageLabel.text = "Authentication success"
} catch let error {
// error
}
}
To to perform an authentication in SwiftUI, create an UIViewControllerRepresentable to inject the UIViewController into a SwiftUI view:
import TeslaSwift
import SwiftUI
struct TeslaWebLogin: UIViewControllerRepresentable {
let api = TeslaSwift()
func makeUIViewController(context: Context) -> TeslaWebLoginViewController {
let (webloginViewController, result) = api.authenticateWeb()
Task { @MainActor in
do {
_ = try await result()
print("Authentication success")
guard api.isAuthenticated else { return }
Task { @MainActor in
do {
let vehicles = try await api.getVehicles()
// post process your vehicles here
} catch {
print("Error",error)
}
}
} catch let error {
print("Error", error)
}
}
return webloginViewController!
}
func updateUIViewController(_ uiViewController: TeslaWebLoginViewController, context: Context) {
}
}
import SwiftUI
struct TeslaLogin: View {
var body: some View {
VStack {
TeslaWebLogin()
}
}
}
After authentication, store the AuthToken in a safe place. The next time the app starts-up you can reuse the token:
let api = TeslaSwift()
api.reuse(token: previousToken)
Example on how to get a list of vehicles with promiseKit
class CarsViewController: ViewController {
func showCars() {
do {
let response = try await api.getVehicles()
self.data = response
self.tableView.reloadData()
} catch let error {
//Process error
}
}
Import the module
import TeslaSwiftStreaming
Import the extension modules if needed (with the previous line)
import TeslaSwiftStreamingCombine
import TeslaSwiftStreamingRx
class CarsViewController: ViewController {
func showStream() {
stream = TeslaStreaming(teslaSwift: api)
do {
for try await event in try await stream.openStream(vehicle: myVehicle) {
switch event {
case .open:
// Open
case .event(let streamEvent):
self.data.append(streamEvent)
self.tableView.reloadData()
case .error(let error):
// Process error
case .disconnet:
break
}
}
} catch let error {
// error
}
// After some events...
stream.closeStream()
}
}
If you need a JSON Encoder and Decoder, the library provides both already configured to be used with Tesla's JSON formats
public let teslaJSONEncoder: JSONEncoder
public let teslaJSONDecoder: JSONDecoder
You can enable debugging by setting: api.debuggingEnabled = true
After the authentication is done, the library will manage the access token. When the token expires the library will request a new token using the refresh token.
If you want to buy a Tesla or signup for the mailing list using my referral as a "thank you" for this library here it is: http://ts.la/joao290
- Key for Tesla (https://itunes.apple.com/us/app/key-for-tesla/id1202595802?mt=8)
- Camper for Tesla (https://itunes.apple.com/us/app/camper-for-tesla/id1227483065?mt=8)
- Power for Tesla (https://itunes.apple.com/us/app/power-for-tesla/id1194710823?mt=8)
- Plus - for Tesla Model S & X (https://itunes.apple.com/us/app/plus-for-tesla-model-s-x/id1187829197?mt=8)
- Nikola for Tesla (https://itunes.apple.com/us/app/nikola-for-tesla/id1244489779?mt=8)
- Charged - for Tesla (https://getcharged.app/)
- TeSlate (https://infinytum.co/)
- Companion for Tesla - oAuth - (https://teslacompanion.app)
- Pilot Log for Tesla (https://itunes.apple.com/us/app/pilot-log-for-Tesla/id1564398488?mt=8)
- EV Companion (https://itunes.apple.com/us/app/ev-companion/id1574209459?mt=8)
- S3XY Key Fob (https://kenmaz.net/tesla-app/)
Missing your app? open a PR or issue
The MIT License (MIT)
Copyright (c) 2016 João Nunes
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.