Инициирование запроса авторизации с областью действия:
https://www.googleapis.com/auth/firebase Ошибка авторизации .messaging
: Der Vorgang konnte nicht abgeschlossen werden.
(org.openid.appauth.general-Fehler -3.)
Идентификаторы client_id, client_secret и redirect_uri взяты из облачной консоли Google (OAuth 2.0-Client-IDs -> Веб-клиент (автоматически создается службой Google)).
Смотрите этот снимок экрана: google облачная консоль
Изменить:
При отправке запроса в моем приложении открывается предупреждение, а затем сразу же закрывается снова, спрашивая меня, хочу ли я предоставить разрешение для входа на сайт google.com.
Возможно, это сообщение об ошибке связано с ним:
"2024- 10-30 18:23:57.498706+0100 Student App[97110:15504024] [Предупреждение]
Попытка загрузить представление контроллера представления во время его
освобождения не допускается и может привести к неопределенному поведению
()"
Код: Выделить всё
import UIKit
import FirebaseDatabase
import FirebaseAuth
import AppAuth
import AppAuthCore
class RemoteNotificationSender: UIViewController {
func sendPushNotification(to topicPath: String, title: String, body: String) {
// property of the containing class
var authState: OIDAuthState?
var access_token = ""
let ref = Database.database().reference()
let urlString = "https://fcm.googleapis.com/v1/projects/fau-students/messages:send"
let url = NSURL(string: urlString)!
let paramString: [String : Any] = ["message" : ["topic": "weather",
"notification" : [
"title" : title,
"body" : body
],
"data" : ["user" : "test_id"]
]
]
let MESSAGING_SCOPE =
"https://www.googleapis.com/auth/firebase.messaging";
let scopes = [MESSAGING_SCOPE];
let authorizationEndpoint = URL(string: "https://accounts.google.com/o/oauth2/v2/auth")!
let tokenEndpoint = URL(string: "https://www.googleapis.com/oauth2/v4/token")!
let configuration = OIDServiceConfiguration(authorizationEndpoint: authorizationEndpoint,
tokenEndpoint: tokenEndpoint)
// perform the auth request...
// builds authentication request
let request_ = OIDAuthorizationRequest(configuration: configuration,
clientId: "",
clientSecret: "",
scopes: scopes,
redirectURL: URL(string: "")!,
responseType: OIDResponseTypeCode,
additionalParameters: nil)
// performs authentication request
print("Initiating authorization request with scope: \(request_.scope ?? "nil")")
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.currentAuthorizationFlow =
OIDAuthState.authState(byPresenting: request_ , presenting: self) { authState, error in
if let authState = authState {
//self.setAuthState(authState)
print("Got authorization tokens. Access token: " +
"\(authState.lastTokenResponse?.accessToken ?? "nil")")
access_token = authState.lastTokenResponse?.accessToken ?? "nil"
} else {
print("Authorization error: \(error?.localizedDescription ?? "Unknown error")")
//self.setAuthState(nil)
}
}
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer " + access_token, forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
do {
if let jsonData = data {
if let jsonDataDict = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
NSLog("FCM: Received data:\n\(jsonDataDict))")
}
}
} catch let err as NSError {
print(err.debugDescription)
}
}
task.resume()
//})
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... -swift-ios
Мобильная версия