@@ -553,6 +553,43 @@ function guidv4($data = null) {
553553
554554```
555555
556+ #### Swift example code
557+
558+ ``` swift
559+ import CryptoKit
560+
561+ let token = 'TTTTTTT'
562+ let secret = 'SSSS'
563+
564+ func getDevices () async throws -> Any {
565+ let hostname = " https://api.switch-bot.com"
566+
567+ var components = URLComponents (string : hostname)!
568+ components.path = " /v1.1/devices"
569+ components.port = 443
570+
571+ var request = URLRequest (url : components.url ! )
572+
573+ request.setValue (" application/json" , forHTTPHeaderField : " Content-Type" )
574+ request.setValue (" utf-8" , forHTTPHeaderField : " charset" )
575+ let timestamp = Int (Date ().timeIntervalSince1970 .rounded () * 1000 ) // Date().timeInterval returns seconds, not milliseconds, since1970
576+ let nonce = UUID ().uuidString
577+
578+ let timeAdjustedToken = token + " \( timestamp ) " + nonce
579+ let key = SymmetricKey (data : Data (secret.utf8 ))
580+ let authenticationCode = HMAC< SHA256> .authenticationCode (for : Data (timeAdjustedToken.utf8 ), using : key)
581+ let signatureToken = Data (authenticationCode).base64EncodedString ()
582+
583+ request.setValue (token, forHTTPHeaderField : " Authorization" )
584+ request.setValue (signatureToken, forHTTPHeaderField : " sign" )
585+ request.setValue (nonce, forHTTPHeaderField : " nonce" )
586+ request.setValue (" \( timestamp ) " , forHTTPHeaderField : " t" )
587+
588+ let (data, response) = try await URLSession.shared .data (for : request)
589+ return try JSONSerialization.jsonObject (with : data)
590+ }
591+ ```
592+
556593## Glossary
557594
558595The following table provides definitions to the terms to be frequently mentioned in the subsequent sections.
0 commit comments