diff --git a/CoreOnly/Tests/FirebasePodTest/FirebasePodTest/AppDelegate.swift b/CoreOnly/Tests/FirebasePodTest/FirebasePodTest/AppDelegate.swift index 066520610c1..fd79728f788 100644 --- a/CoreOnly/Tests/FirebasePodTest/FirebasePodTest/AppDelegate.swift +++ b/CoreOnly/Tests/FirebasePodTest/FirebasePodTest/AppDelegate.swift @@ -62,7 +62,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { // Called when the user discards a scene session. - // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. - // Use this method to release any resources that were specific to the discarded scenes, as they will not return. + // If any sessions were discarded while the application was not running, this will be called + // shortly after application:didFinishLaunchingWithOptions. + // Use this method to release any resources that were specific to the discarded scenes, as they + // will not return. } } diff --git a/CoreOnly/Tests/FirebasePodTest/FirebasePodTest/SceneDelegate.swift b/CoreOnly/Tests/FirebasePodTest/FirebasePodTest/SceneDelegate.swift index 63997a730cc..c45e24a9d37 100644 --- a/CoreOnly/Tests/FirebasePodTest/FirebasePodTest/SceneDelegate.swift +++ b/CoreOnly/Tests/FirebasePodTest/FirebasePodTest/SceneDelegate.swift @@ -20,22 +20,26 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. - // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. - // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). + // Use this method to optionally configure and attach the UIWindow `window` to the provided + // UIWindowScene `scene`. If using a storyboard, the `window` property will automatically + // be initialized and attached to the scene. This delegate does not imply the connecting + // scene or session are new (see `application:configurationForConnectingSceneSession` + // instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. - // Release any resources associated with this scene that can be re-created the next time the scene connects. - // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). + // Release any resources associated with this scene that can be re-created the next time the + // scene connects. The scene may re-connect later, as its session was not neccessarily + // discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. - // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. + // Use this method to restart any tasks that were paused (or not yet started) when the scene was + // inactive. } func sceneWillResignActive(_ scene: UIScene) { @@ -50,7 +54,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. - // Use this method to save data, release shared resources, and store enough scene-specific state information - // to restore the scene back to its current state. + // Use this method to save data, release shared resources, and store enough scene-specific state + // information to restore the scene back to its current state. } } diff --git a/Example/watchOSSample/ServiceExtension/NotificationService.swift b/Example/watchOSSample/ServiceExtension/NotificationService.swift index 945eba4ade7..d961bea31d3 100644 --- a/Example/watchOSSample/ServiceExtension/NotificationService.swift +++ b/Example/watchOSSample/ServiceExtension/NotificationService.swift @@ -37,7 +37,8 @@ class NotificationService: UNNotificationServiceExtension { override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. - // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. + // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the + // original push payload will be used. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } diff --git a/FirebaseAppCheck/Apps/AppCheckCustomProvideApp/AppCheckCustomProvideApp/MyAppCheckProvider.swift b/FirebaseAppCheck/Apps/AppCheckCustomProvideApp/AppCheckCustomProvideApp/MyAppCheckProvider.swift index 8587ee99b93..b619295f9a2 100644 --- a/FirebaseAppCheck/Apps/AppCheckCustomProvideApp/AppCheckCustomProvideApp/MyAppCheckProvider.swift +++ b/FirebaseAppCheck/Apps/AppCheckCustomProvideApp/AppCheckCustomProvideApp/MyAppCheckProvider.swift @@ -21,7 +21,8 @@ import FirebaseAppCheck class MyAppCheckProvider: NSObject, AppCheckProvider { func getToken(completion handler: @escaping AppCheckTokenHandler) { DispatchQueue.main.async { - // Create or request Firebase App Check token. Usually the token is requested from your server. + // Create or request Firebase App Check token. Usually the token is requested from your + // server. let myToken = AppCheckToken( token: "MyToken", expirationDate: Date(timeIntervalSinceNow: 60 * 60) diff --git a/FirebaseAppCheck/Apps/AppCheckCustomProvideApp/AppCheckCustomProvideApp/SceneDelegate.swift b/FirebaseAppCheck/Apps/AppCheckCustomProvideApp/AppCheckCustomProvideApp/SceneDelegate.swift index 99224314494..7a7c678ab92 100644 --- a/FirebaseAppCheck/Apps/AppCheckCustomProvideApp/AppCheckCustomProvideApp/SceneDelegate.swift +++ b/FirebaseAppCheck/Apps/AppCheckCustomProvideApp/AppCheckCustomProvideApp/SceneDelegate.swift @@ -22,9 +22,11 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. - // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. - // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). + // Use this method to optionally configure and attach the UIWindow `window` to the provided + // UIWindowScene `scene`. If using a storyboard, the `window` property will automatically + // be initialized and attached to the scene. This delegate does not imply the connecting + // scene or session are new (see `application:configurationForConnectingSceneSession` + // instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() @@ -41,13 +43,15 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. - // Release any resources associated with this scene that can be re-created the next time the scene connects. - // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). + // Release any resources associated with this scene that can be re-created the next time the + // scene connects. The scene may re-connect later, as its session was not necessarily + // discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. - // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. + // Use this method to restart any tasks that were paused (or not yet started) when the scene was + // inactive. } func sceneWillResignActive(_ scene: UIScene) { @@ -62,7 +66,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. - // Use this method to save data, release shared resources, and store enough scene-specific state information - // to restore the scene back to its current state. + // Use this method to save data, release shared resources, and store enough scene-specific state + // information to restore the scene back to its current state. } } diff --git a/FirebaseAppCheck/Apps/FIRAppCheckTestApp/FIRAppCheckTestApp/AppDelegate.swift b/FirebaseAppCheck/Apps/FIRAppCheckTestApp/FIRAppCheckTestApp/AppDelegate.swift index ac45d49b8bb..b57f446b372 100644 --- a/FirebaseAppCheck/Apps/FIRAppCheckTestApp/FIRAppCheckTestApp/AppDelegate.swift +++ b/FirebaseAppCheck/Apps/FIRAppCheckTestApp/FIRAppCheckTestApp/AppDelegate.swift @@ -58,8 +58,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { // Called when the user discards a scene session. - // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. - // Use this method to release any resources that were specific to the discarded scenes, as they will not return. + // If any sessions were discarded while the application was not running, this will be called + // shortly after application:didFinishLaunchingWithOptions. + // Use this method to release any resources that were specific to the discarded scenes, as they + // will not return. } // MARK: App Check providers diff --git a/FirebaseAppCheck/Apps/FIRAppCheckTestApp/FIRAppCheckTestApp/SceneDelegate.swift b/FirebaseAppCheck/Apps/FIRAppCheckTestApp/FIRAppCheckTestApp/SceneDelegate.swift index 92dab56716f..29f854fb00a 100644 --- a/FirebaseAppCheck/Apps/FIRAppCheckTestApp/FIRAppCheckTestApp/SceneDelegate.swift +++ b/FirebaseAppCheck/Apps/FIRAppCheckTestApp/FIRAppCheckTestApp/SceneDelegate.swift @@ -21,22 +21,26 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. - // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. - // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). + // Use this method to optionally configure and attach the UIWindow `window` to the provided + // UIWindowScene `scene`. If using a storyboard, the `window` property will automatically + // be initialized and attached to the scene. This delegate does not imply the connecting + // scene or session are new (see `application:configurationForConnectingSceneSession` + // instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. - // Release any resources associated with this scene that can be re-created the next time the scene connects. - // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). + // Release any resources associated with this scene that can be re-created the next time the + // scene connects. The scene may re-connect later, as its session was not necessarily + // discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. - // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. + // Use this method to restart any tasks that were paused (or not yet started) when the scene was + // inactive. } func sceneWillResignActive(_ scene: UIScene) { @@ -51,7 +55,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. - // Use this method to save data, release shared resources, and store enough scene-specific state information - // to restore the scene back to its current state. + // Use this method to save data, release shared resources, and store enough scene-specific state + // information to restore the scene back to its current state. } } diff --git a/FirebaseAppDistributionInternal/Sources/ApiService.swift b/FirebaseAppDistributionInternal/Sources/ApiService.swift index 6f51ec18b6f..237f028eee8 100644 --- a/FirebaseAppDistributionInternal/Sources/ApiService.swift +++ b/FirebaseAppDistributionInternal/Sources/ApiService.swift @@ -122,8 +122,10 @@ struct FeedbackReport: Codable { }) } - @objc(fetchReleasesWithCompletion:) public static func fetchReleases(completion: @escaping (_ releases: [Any]?, - _ error: Error?) + @objc(fetchReleasesWithCompletion:) public static func fetchReleases(completion: @escaping (_ releases: [ + Any, + ]?, + _ error: Error?) -> Void) { guard let app = FirebaseApp.app() else { return diff --git a/FirebaseAppDistributionInternal/Sources/InAppFeedback.swift b/FirebaseAppDistributionInternal/Sources/InAppFeedback.swift index 6ef3e3da71f..0cef84e8940 100644 --- a/FirebaseAppDistributionInternal/Sources/InAppFeedback.swift +++ b/FirebaseAppDistributionInternal/Sources/InAppFeedback.swift @@ -88,8 +88,8 @@ import Photos static func getPhotoPermissionIfNecessary(completionHandler: @escaping (_ authorized: Bool) -> Void) { if #available(iOS 14, *) { - // The iOS 14 API is used to prompt users for permission if they previously provided limited access, - // but have now taken an additional screenshot. + // The iOS 14 API is used to prompt users for permission if they previously provided limited + // access, but have now taken an additional screenshot. guard PHPhotoLibrary.authorizationStatus(for: .readWrite) != .authorized else { completionHandler(true) return diff --git a/FirebaseAuth/Tests/Sample/SwiftApiTests/FacebookTests.swift b/FirebaseAuth/Tests/Sample/SwiftApiTests/FacebookTests.swift index 9e6d1013b53..19ebe14537e 100644 --- a/FirebaseAuth/Tests/Sample/SwiftApiTests/FacebookTests.swift +++ b/FirebaseAuth/Tests/Sample/SwiftApiTests/FacebookTests.swift @@ -113,9 +113,8 @@ import XCTest // } // #endif // -// /// ** Creates a Facebook testing account using Facebook Graph API and return a dictionary that -// // * constains "id", "access_token", "login_url", "email" and "password" of the created account. -// // */ +// /// Creates a Facebook testing account using Facebook Graph API and return a dictionary that +// /// constrains "id", "access_token", "login_url", "email" and "password" of the created account. // func createFacebookTestingAccount() -> [String: Any] { // var returnValue: [String: Any] = [:] // let urltoCreateTestUser = "https://graph.facebook.com/\(Credentials.kFacebookAppID)" + @@ -154,9 +153,9 @@ import XCTest // // #if compiler(>=5.5.2) && canImport(_Concurrency) // @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *) -// /// ** Creates a Facebook testing account using Facebook Graph API and return a dictionary that -// // * constains "id", "access_token", "login_url", "email" and "password" of the created account. -// // */ +// /// Creates a Facebook testing account using Facebook Graph API and return a dictionary that +// /// constains "id", "access_token", "login_url", "email" and "password" of the created +// /// account. // func createFacebookTestingAccountAsync() async throws -> [String: Any] { // let urltoCreateTestUser = "https://graph.facebook.com/\(Credentials.kFacebookAppID)" + // "/accounts/test-users" diff --git a/FirebaseAuth/Tests/Sample/SwiftApiTests/GoogleTests.swift b/FirebaseAuth/Tests/Sample/SwiftApiTests/GoogleTests.swift index 12b22a3c0af..b6819d48677 100644 --- a/FirebaseAuth/Tests/Sample/SwiftApiTests/GoogleTests.swift +++ b/FirebaseAuth/Tests/Sample/SwiftApiTests/GoogleTests.swift @@ -50,11 +50,11 @@ class GoogleTests: TestsBase { } #endif - /// ** Sends http request to Google OAuth2 token server to use refresh token to exchange for Google - // * access token. Returns a dictionary that constains "access_token", "token_type", "expires_in" and - // * sometimes the "id_token". (The id_token is not guaranteed to be returned during a refresh - // * exchange; see https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse) - // */ + /// Sends http request to Google OAuth2 token server to use refresh token to exchange for Google + /// access token. + /// Returns a dictionary that constains "access_token", "token_type", "expires_in" and sometimes + /// the "id_token". (The id_token is not guaranteed to be returned during a refresh exchange; see + /// https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse) func getGoogleAccessToken() -> [String: Any] { var returnValue: [String: Any] = [:] let googleOauth2TokenServerUrl = "https://www.googleapis.com/oauth2/v4/token" @@ -86,11 +86,11 @@ class GoogleTests: TestsBase { #if compiler(>=5.5.2) && canImport(_Concurrency) @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *) - /// ** Sends http request to Google OAuth2 token server to use refresh token to exchange for Google - // * access token. Returns a dictionary that constains "access_token", "token_type", "expires_in" and - // * sometimes the "id_token". (The id_token is not guaranteed to be returned during a refresh - // * exchange; see https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse) - // */ + /// Sends http request to Google OAuth2 token server to use refresh token to exchange for Google + /// access token. + /// Returns a dictionary that constains "access_token", "token_type", "expires_in" and sometimes + /// the "id_token". (The id_token is not guaranteed to be returned during a refresh exchange; + /// see https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse) func getGoogleAccessTokenAsync() async throws -> [String: Any] { let googleOauth2TokenServerUrl = "https://www.googleapis.com/oauth2/v4/token" let bodyString = "client_id=\(Credentials.kGoogleClientID)&grant_type=refresh_token" + diff --git a/FirebaseCombineSwift/Sources/Auth/Auth+Combine.swift b/FirebaseCombineSwift/Sources/Auth/Auth+Combine.swift index 27ec42289db..fce4a3ddfaf 100644 --- a/FirebaseCombineSwift/Sources/Auth/Auth+Combine.swift +++ b/FirebaseCombineSwift/Sources/Auth/Auth+Combine.swift @@ -35,7 +35,8 @@ /// /// The publisher will emit events on the **main** thread. /// - /// - Returns: A publisher emitting a `User` instance (if the user has signed in) or `nil` (if the user has signed out). + /// - Returns: A publisher emitting a `User` instance (if the user has signed in) or `nil` (if + /// the user has signed out). /// The publisher will emit on the *main* thread. func authStateDidChangePublisher() -> AnyPublisher { let subject = PassthroughSubject() @@ -79,8 +80,10 @@ /// /// The publisher will emit events on the **main** thread. /// - /// - Parameter user: The user object to be set as the current user of the calling Auth instance. - /// - Returns: A publisher that emits when the user of the calling Auth instance has been updated or + /// - Parameter user: The user object to be set as the current user of the calling Auth + /// instance. + /// - Returns: A publisher that emits when the user of the calling Auth instance has been + /// updated or /// an error was encountered. The publisher will emit on the **main** thread. @discardableResult func updateCurrentUser(_ user: User) -> Future { @@ -97,14 +100,16 @@ // MARK: - Anonymous Authentication - /// Asynchronously creates an anonymous user and assigns it as the calling Auth instance's current user. + /// Asynchronously creates an anonymous user and assigns it as the calling Auth instance's + /// current user. /// /// If there is already an anonymous user signed in, that user will be returned instead. /// If there is any other existing user signed in, that user will be signed out. /// /// The publisher will emit events on the **main** thread. /// - /// - Returns: A publisher that emits the result of the sign in flow. The publisher will emit on the *main* thread. + /// - Returns: A publisher that emits the result of the sign in flow. The publisher will emit on + /// the *main* thread. /// - Remark: /// Possible error codes: /// - `AuthErrorCodeOperationNotAllowed` - Indicates that anonymous accounts are @@ -133,7 +138,8 @@ /// - Parameters: /// - email: The user's email address. /// - password: The user's desired password. - /// - Returns: A publisher that emits the result of the sign in flow. The publisher will emit on the *main* thread. + /// - Returns: A publisher that emits the result of the sign in flow. The publisher will emit on + /// the *main* thread. /// - Remark: /// Possible error codes: /// - `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed. @@ -168,7 +174,8 @@ /// - Parameters: /// - email: The user's email address. /// - password: The user's password. - /// - Returns: A publisher that emits the result of the sign in flow. The publisher will emit on the *main* thread. + /// - Returns: A publisher that emits the result of the sign in flow. The publisher will emit on + /// the *main* thread. /// - Remark: /// Possible error codes: /// - `AuthErrorCodeOperationNotAllowed` - Indicates that email and password @@ -203,7 +210,8 @@ /// - Parameters: /// - email: The user's email address. /// - link: The email sign-in link. - /// - Returns: A publisher that emits the result of the sign in flow. The publisher will emit on the *main* thread. + /// - Returns: A publisher that emits the result of the sign in flow. The publisher will emit on + /// the *main* thread. /// - Remark: /// Possible error codes: /// - `AuthErrorCodeOperationNotAllowed` - Indicates that email and password @@ -236,7 +244,8 @@ /// - email: The email address of the user. /// - actionCodeSettings: An `ActionCodeSettings` object containing settings related to /// handling action codes. - /// - Returns: A publisher that emits whether the call was successful or not. The publisher will emit on the *main* thread. + /// - Returns: A publisher that emits whether the call was successful or not. The publisher will + /// emit on the *main* thread. @available(watchOS, unavailable) @discardableResult func sendSignInLink(toEmail email: String, @@ -279,17 +288,21 @@ // MARK: - Password Reset - /// Resets the password given a code sent to the user outside of the app and a new password for the user. + /// Resets the password given a code sent to the user outside of the app and a new password for + /// the user. /// /// The publisher will emit events on the **main** thread. /// /// - Parameters: /// - code: Out-of-band (OOB) code given to the user outside of the app. /// - newPassword: The new password. - /// - Returns: A publisher that emits whether the call was successful or not. The publisher will emit on the *main* thread. + /// - Returns: A publisher that emits whether the call was successful or not. The publisher will + /// emit on the *main* thread. /// - Remark: Possible error codes: - /// - `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is considered too weak. - /// - `AuthErrorCodeOperationNotAllowed` - Indicates the admin disabled sign in with the specified identity provider. + /// - `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is considered + /// too weak. + /// - `AuthErrorCodeOperationNotAllowed` - Indicates the admin disabled sign in with the + /// specified identity provider. /// - `AuthErrorCodeExpiredActionCode` - Indicates the OOB code is expired. /// - `AuthErrorCodeInvalidActionCode` - Indicates the OOB code is invalid. /// @@ -313,8 +326,10 @@ /// The publisher will emit events on the **main** thread. /// /// - Parameter code: The password reset code to be verified. - /// - Returns: A publisher that emits an error if the code could not be verified. If the code could be - /// verified, the publisher will emit the email address of the account the code was issued for. + /// - Returns: A publisher that emits an error if the code could not be verified. If the code + /// could be + /// verified, the publisher will emit the email address of the account the code was issued + /// for. /// The publisher will emit on the *main* thread. @discardableResult func verifyPasswordResetCode(_ code: String) -> Future { @@ -334,7 +349,8 @@ /// The publisher will emit events on the **main** thread. /// /// - Parameter code: The out of band code to check validity. - /// - Returns: A publisher that emits the email address of the account the code was issued for or an error if + /// - Returns: A publisher that emits the email address of the account the code was issued for + /// or an error if /// the code could not be verified. The publisher will emit on the *main* thread. @discardableResult func checkActionCode(code: String) -> Future { @@ -354,8 +370,10 @@ /// The publisher will emit events on the **main** thread. /// /// - Parameter code: The out-of-band (OOB) code to be applied. - /// - Returns: A publisher that emits an error if the code could not be applied. The publisher will emit on the *main* thread. - /// - Remark: This method will not work for out-of-band codes which require an additional parameter, + /// - Returns: A publisher that emits an error if the code could not be applied. The publisher + /// will emit on the *main* thread. + /// - Remark: This method will not work for out-of-band codes which require an additional + /// parameter, /// such as password reset codes. @discardableResult func applyActionCode(code: String) -> Future { @@ -375,11 +393,15 @@ /// The publisher will emit events on the **main** thread. /// /// - Parameter email: The email address of the user. - /// - Returns: A publisher that emits whether the call was successful or not. The publisher will emit on the *main* thread. + /// - Returns: A publisher that emits whether the call was successful or not. The publisher will + /// emit on the *main* thread. /// - Remark: Possible error codes: - /// - `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was sent in the request. - /// - `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in the console for this action. - /// - `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for sending update email. + /// - `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was sent in + /// the request. + /// - `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in the console + /// for this action. + /// - `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for sending + /// update email. /// /// See `AuthErrors` for a list of error codes that are common to all API methods @discardableResult @@ -400,20 +422,28 @@ /// The publisher will emit events on the **main** thread. /// /// - Parameter email: The email address of the user. - /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to + /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related + /// to /// handling action codes. - /// - Returns: A publisher that emits whether the call was successful or not. The publisher will emit on the *main* thread. + /// - Returns: A publisher that emits whether the call was successful or not. The publisher will + /// emit on the *main* thread. /// - Remark: Possible error codes: - /// - `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was sent in the request. - /// - `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in the console for this action. - /// - `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for sending update email. + /// - `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was sent in + /// the request. + /// - `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in the console + /// for this action. + /// - `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for sending + /// update email. /// - `AuthErrorCodeMissingIosBundleID` - Indicates that the iOS bundle ID is missing /// when `handleCodeInApp` is set to YES. - /// - `AuthErrorCodeMissingAndroidPackageName` - Indicates that the android package name is missing + /// - `AuthErrorCodeMissingAndroidPackageName` - Indicates that the android package name is + /// missing /// when the `androidInstallApp` flag is set to true. - /// - `AuthErrorCodeUnauthorizedDomain` - Indicates that the domain specified in the continue URL is not whitelisted + /// - `AuthErrorCodeUnauthorizedDomain` - Indicates that the domain specified in the continue + /// URL is not whitelisted /// in the Firebase console. - /// - `AuthErrorCodeInvalidContinueURI` - Indicates that the domain specified in the continue URI is not valid. + /// - `AuthErrorCodeInvalidContinueURI` - Indicates that the domain specified in the continue + /// URI is not valid. /// /// See `AuthErrors` for a list of error codes that are common to all API methods @discardableResult @@ -440,28 +470,38 @@ /// - Parameters: /// - provider: An instance of an auth provider used to initiate the sign-in flow. /// - uiDelegate: Optionally, an instance of a class conforming to the `AuthUIDelegate` - /// protocol. This is used for presenting the web context. If `nil`, a default `AuthUIDelegate` + /// protocol. This is used for presenting the web context. If `nil`, a default + /// `AuthUIDelegate` /// will be used. /// - Returns: A publisher that emits an `AuthDataResult` when the sign-in flow completed /// successfully, or an error otherwise. The publisher will emit on the *main* thread. /// - Remark: Possible error codes: - /// - `AuthErrorCodeOperationNotAllowed` - Indicates that email and password accounts are not enabled. + /// - `AuthErrorCodeOperationNotAllowed` - Indicates that email and password accounts are + /// not enabled. /// Enable them in the Auth section of the Firebase console. /// - `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled. /// - `AuthErrorCodeWebNetworkRequestFailed` - Indicates that a network request within a /// `SFSafariViewController` or `WKWebView` failed. /// - `AuthErrorCodeWebInternalError` - Indicates that an internal error occurred within a /// `SFSafariViewController` or `WKWebView`.` - /// - `AuthErrorCodeWebSignInUserInteractionFailure` - Indicates a general failure during a web sign-in flow.` - /// - `AuthErrorCodeWebContextAlreadyPresented` - Indicates that an attempt was made to present a new web + /// - `AuthErrorCodeWebSignInUserInteractionFailure` - Indicates a general failure during a + /// web sign-in flow.` + /// - `AuthErrorCodeWebContextAlreadyPresented` - Indicates that an attempt was made to + /// present a new web /// context while one was already being presented.` - /// - `AuthErrorCodeWebContextCancelled` - Indicates that the URL presentation was cancelled prematurely + /// - `AuthErrorCodeWebContextCancelled` - Indicates that the URL presentation was cancelled + /// prematurely /// by the user.` - /// - `AuthErrorCodeAccountExistsWithDifferentCredential` - Indicates the email asserted by the credential - /// (e.g. the email in a Facebook access token) is already in use by an existing account that cannot be - /// authenticated with this sign-in method. Call `fetchProvidersForEmail` for this user’s email and then - /// prompt them to sign in with any of the sign-in providers returned. This error will only be thrown if - /// the "One account per email address" setting is enabled in the Firebase console, under Auth settings. + /// - `AuthErrorCodeAccountExistsWithDifferentCredential` - Indicates the email asserted by + /// the credential + /// (e.g. the email in a Facebook access token) is already in use by an existing account + /// that cannot be + /// authenticated with this sign-in method. Call `fetchProvidersForEmail` for this user’s + /// email and then + /// prompt them to sign in with any of the sign-in providers returned. This error will + /// only be thrown if + /// the "One account per email address" setting is enabled in the Firebase console, under + /// Auth settings. /// /// See `AuthErrors` for a list of error codes that are common to all API methods @discardableResult diff --git a/FirebaseCombineSwift/Sources/Auth/MultiFactor+Combine.swift b/FirebaseCombineSwift/Sources/Auth/MultiFactor+Combine.swift index 9f30d6d75f3..69d718516a0 100644 --- a/FirebaseCombineSwift/Sources/Auth/MultiFactor+Combine.swift +++ b/FirebaseCombineSwift/Sources/Auth/MultiFactor+Combine.swift @@ -30,7 +30,8 @@ /// The publisher will emit events on the **main** thread. /// /// - Returns: A publisher that emits a `MultiFactorSession` for a second factor - /// enrollment operation. This is used to identify the current user trying to enroll a second factor. The publisher will emit on + /// enrollment operation. This is used to identify the current user trying to enroll a + /// second factor. The publisher will emit on /// the *main* thread. @discardableResult func getSession() -> Future { @@ -54,7 +55,8 @@ /// - assertion: The base class for asserting ownership of a second factor. /// - displayName: An optional display name associated with the multi factor to enroll. /// - /// - Returns: A publisher that emits whether the call was successful or not. The publisher will emit on the *main* thread. + /// - Returns: A publisher that emits whether the call was successful or not. The publisher + /// will emit on the *main* thread. @discardableResult func enroll(with assertion: MultiFactorAssertion, displayName: String?) -> Future { @@ -73,8 +75,10 @@ /// /// The publisher will emit events on the **main** thread. /// - /// - Parameter factorInfo: The structure used to represent a second factor entity from a client perspective. - /// - Returns: A publisher that emits when the request to send the unenrollment verification email is complete. The publisher + /// - Parameter factorInfo: The structure used to represent a second factor entity from a + /// client perspective. + /// - Returns: A publisher that emits when the request to send the unenrollment verification + /// email is complete. The publisher /// will emit on the *main* thread. @discardableResult func unenroll(with factorInfo: MultiFactorInfo) -> Future { @@ -93,7 +97,8 @@ /// /// The publisher will emit events on the **main** thread. /// - /// - Returns: A publisher that emits when the request to send the unenrollment verification email is complete. + /// - Returns: A publisher that emits when the request to send the unenrollment verification + /// email is complete. /// The publisher will emit on the *main* thread. @discardableResult func unenroll(withFactorUID factorUID: String) -> Future { diff --git a/FirebaseCombineSwift/Sources/Auth/MultiFactorResolver+Combine.swift b/FirebaseCombineSwift/Sources/Auth/MultiFactorResolver+Combine.swift index 8e72e20923c..0cf2fcb95b0 100644 --- a/FirebaseCombineSwift/Sources/Auth/MultiFactorResolver+Combine.swift +++ b/FirebaseCombineSwift/Sources/Auth/MultiFactorResolver+Combine.swift @@ -25,7 +25,8 @@ @available(tvOS, unavailable) @available(watchOS, unavailable) public extension MultiFactorResolver { - /// A helper function that helps users sign in with a second factor using a `MultiFactorAssertion`. + /// A helper function that helps users sign in with a second factor using a + /// `MultiFactorAssertion`. /// This assertion confirms that the user has successfully completed the second factor. /// /// - Parameter assertion: The base class for asserting ownership of a second factor. diff --git a/FirebaseCombineSwift/Sources/Auth/PhoneAuthProvider+Combine.swift b/FirebaseCombineSwift/Sources/Auth/PhoneAuthProvider+Combine.swift index 3ea57ea96f2..9e718abcd0d 100644 --- a/FirebaseCombineSwift/Sources/Auth/PhoneAuthProvider+Combine.swift +++ b/FirebaseCombineSwift/Sources/Auth/PhoneAuthProvider+Combine.swift @@ -35,8 +35,8 @@ /// /// - Parameters: /// - phoneNumber: The phone number to be verified. - /// - uiDelegate: An object used to present the `SFSafariViewController`. The object is retained - /// by this method until the completion block is executed. + /// - uiDelegate: An object used to present the `SFSafariViewController`. The object is + /// retained by this method until the completion block is executed. /// /// - Returns: A publisher that emits an `VerificationID` when the verification flow completed /// successfully, or an error otherwise. The publisher will emit on the *main* thread. @@ -72,11 +72,11 @@ /// /// - Parameters: /// - phoneNumber: The phone number to be verified. - /// - uiDelegate: An object used to present the `SFSafariViewController`. The object is retained - /// by this method until the completion block is executed. - /// - session: A session to identify the MFA flow. For enrollment, this identifies the user - /// trying to enroll. For sign-in, this identifies that the user already passed the first - /// factor challenge. + /// - uiDelegate: An object used to present the `SFSafariViewController`. The object is + /// retained by this method until the completion block is executed. + /// - session: A session to identify the MFA flow. For enrollment, this identifies the + /// user trying to enroll. For sign-in, this identifies that the user already passed the + /// first factor challenge. /// /// - Returns: A publisher that emits an `VerificationID` when the verification flow completed /// successfully, or an error otherwise. The publisher will emit on the *main* thread. @@ -117,10 +117,12 @@ /// /// - Parameters: /// - phoneNumber: The phone number to be verified. - /// - UIDelegate: An object used to present the SFSafariViewController. The object is retained - /// by this method until the completion block is executed. - /// - multiFactorSession: session A session to identify the MFA flow. For enrollment, this identifies the user - /// trying to enroll. For sign-in, this identifies that the user already passed the first factor challenge. + /// - UIDelegate: An object used to present the SFSafariViewController. The object is + /// retained by this method until the completion block is executed. + /// - multiFactorSession: session A session to identify the MFA flow. For enrollment, this + /// identifies the user trying to enroll. For sign-in, this identifies that the user + /// already + /// passed the first factor challenge. /// - Returns: A publisher that emits an `VerificationID` when the verification flow completed /// successfully, or an error otherwise. The publisher will emit on the *main* thread. @discardableResult diff --git a/FirebaseCombineSwift/Sources/Auth/User+Combine.swift b/FirebaseCombineSwift/Sources/Auth/User+Combine.swift index 43aad14fcf0..4dfb4fb7d53 100644 --- a/FirebaseCombineSwift/Sources/Auth/User+Combine.swift +++ b/FirebaseCombineSwift/Sources/Auth/User+Combine.swift @@ -29,12 +29,13 @@ /// - Returns: A publisher that emits an `AuthDataResult` when the association flow completed /// successfully, or an error otherwise. The publisher will emit on the *main* thread. /// - Remark: Possible error codes: - /// - `FIRAuthErrorCodeProviderAlreadyLinked` - Indicates an attempt to link a provider of a type - /// already linked to this account. - /// - `FIRAuthErrorCodeCredentialAlreadyInUse` - Indicates an attempt to link with a credential - /// that has already been linked with a different Firebase account. - /// - `FIRAuthErrorCodeOperationNotAllowed` - Indicates that accounts with the identity provider - /// represented by the credential are not enabled. Enable them in the Auth section of the Firebase console. + /// - `FIRAuthErrorCodeProviderAlreadyLinked` - Indicates an attempt to link a provider of a + /// type already linked to this account. + /// - `FIRAuthErrorCodeCredentialAlreadyInUse` - Indicates an attempt to link with a + /// credential that has already been linked with a different Firebase account. + /// - `FIRAuthErrorCodeOperationNotAllowed` - Indicates that accounts with the identity + /// provider represented by the credential are not enabled. Enable them in the Auth + /// section of the Firebase console. /// /// See `FIRAuthErrors` for a list of error codes that are common to all FIRUser methods. func link(with credential: AuthCredential) -> Future { @@ -54,12 +55,14 @@ /// /// The publisher will emit events on the **main** thread. /// - /// - Parameter credential: A user-supplied credential, which will be validated by the server. This can be - /// a successful third-party identity provider sign-in, or an email address and password. - /// - Returns: A publisher that emits an `AuthDataResult` when the reauthentication flow completed - /// successfully, or an error otherwise. - /// - Remark: If the user associated with the supplied credential is different from the current user, or if the validation - /// of the supplied credentials fails; an error is returned and the current user remains signed in. + /// - Parameter credential: A user-supplied credential, which will be validated by the server. + /// This can be a successful third-party identity provider sign-in, or an email address and + /// password. + /// - Returns: A publisher that emits an `AuthDataResult` when the reauthentication flow + /// completed successfully, or an error otherwise. + /// - Remark: If the user associated with the supplied credential is different from the current + /// user, or if the validation of the supplied credentials fails; an error is returned and the + /// current user remains signed in. /// /// Possible error codes: /// @@ -159,8 +162,8 @@ /// /// The publisher will emit events on the **main** thread. /// - /// - Parameter actionCodeSettings: An `FIRActionCodeSettings` object containing settings related to - /// handling action codes. + /// - Parameter actionCodeSettings: An `FIRActionCodeSettings` object containing settings + /// related to handling action codes. /// - Returns: A publisher that emits no type when the verification flow completed /// successfully, or an error otherwise. /// diff --git a/FirebaseCombineSwift/Sources/Firestore/CollectionReference+Combine.swift b/FirebaseCombineSwift/Sources/Firestore/CollectionReference+Combine.swift index 402186e28cb..32dc0004dc7 100644 --- a/FirebaseCombineSwift/Sources/Firestore/CollectionReference+Combine.swift +++ b/FirebaseCombineSwift/Sources/Firestore/CollectionReference+Combine.swift @@ -32,9 +32,9 @@ /// automatically. /// /// - Parameter data: A `Dictionary` containing the data for the new document. - /// - Returns: A publisher emitting a `DocumentReference` value once the document has been successfully - /// written to the server. This publisher will not emit while the client is offline, though - /// local changes will be visible immediately. + /// - Returns: A publisher emitting a `DocumentReference` value once the document has been + /// successfully written to the server. This publisher will not emit while the + /// client is offline, though local changes will be visible immediately. func addDocument(data: [String: Any]) -> Future { var reference: DocumentReference? @@ -57,9 +57,9 @@ /// - Parameters: /// - value: An instance of `Encodable` to be encoded to a document. /// - encoder: An encoder instance to use to run the encoding. - /// - Returns: A publisher emitting a `DocumentReference` value once the document has been successfully - /// written to the server. This publisher will not emit while the client is offline, though - /// local changes will be visible immediately. + /// - Returns: A publisher emitting a `DocumentReference` value once the document has been + /// successfully written to the server. This publisher will not emit while the + /// client is offline, though local changes will be visible immediately. func addDocument(from value: T, encoder: Firestore.Encoder = Firestore .Encoder()) -> Future< diff --git a/FirebaseCombineSwift/Sources/Firestore/DocumentReference+Combine.swift b/FirebaseCombineSwift/Sources/Firestore/DocumentReference+Combine.swift index 65df8e1402e..5d853fde1c1 100644 --- a/FirebaseCombineSwift/Sources/Firestore/DocumentReference+Combine.swift +++ b/FirebaseCombineSwift/Sources/Firestore/DocumentReference+Combine.swift @@ -99,9 +99,9 @@ #if canImport(FirebaseFirestoreSwift) - /// Encodes an instance of `Encodable` and overwrites the encoded data to the document referred - /// by this `DocumentReference`. If no document exists, it is created. If a document already - /// exists, it is overwritten. + /// Encodes an instance of `Encodable` and overwrites the encoded data to the document + /// referred by this `DocumentReference`. If no document exists, it is created. If a + /// document already exists, it is overwritten. /// /// - Parameters: /// - value: An instance of `Encodable` to be encoded to a document. @@ -129,9 +129,11 @@ } } - /// Encodes an instance of `Encodable` and overwrites the encoded data to the document referred + /// Encodes an instance of `Encodable` and overwrites the encoded data to the document + /// referred /// by this `DocumentReference`. If no document exists, it is created. If a document already - /// exists, it is overwritten. If you pass `merge: true`, the provided Encodable will be merged + /// exists, it is overwritten. If you pass `merge: true`, the provided Encodable will be + /// merged /// into any existing document. /// /// - Parameters: @@ -162,7 +164,8 @@ } /// Encodes an instance of `Encodable` and writes the encoded data to the document referred by - /// this `DocumentReference` by only replacing the fields specified under mergeFields. Any field + /// this `DocumentReference` by only replacing the fields specified under mergeFields. Any + /// field /// that is not specified in mergeFields is ignored and remains untouched. If the document /// doesn’t yet exist, this method creates it and then sets the data. /// diff --git a/FirebaseCombineSwift/Sources/Firestore/Query+Combine.swift b/FirebaseCombineSwift/Sources/Firestore/Query+Combine.swift index 2cc6fd48560..5ad9b8587fc 100644 --- a/FirebaseCombineSwift/Sources/Firestore/Query+Combine.swift +++ b/FirebaseCombineSwift/Sources/Firestore/Query+Combine.swift @@ -25,7 +25,8 @@ /// Reads the documents matching this query. /// /// - Parameter source: Indicates whether the results should be fetched from the cache only - /// (`Source.cache`), the server only (`Source.server`), or to attempt the server and fall back + /// (`Source.cache`), the server only (`Source.server`), or to attempt the server and fall + /// back /// to the cache (`Source.default`). /// - Returns: A publisher emitting a `QuerySnapshot` instance. func getDocuments(source: FirestoreSource = .default) -> Future { diff --git a/FirebaseCombineSwift/Sources/Functions/HTTPSCallable+Combine.swift b/FirebaseCombineSwift/Sources/Functions/HTTPSCallable+Combine.swift index b9a5f88e97f..7841583a3a9 100644 --- a/FirebaseCombineSwift/Sources/Functions/HTTPSCallable+Combine.swift +++ b/FirebaseCombineSwift/Sources/Functions/HTTPSCallable+Combine.swift @@ -27,14 +27,17 @@ /// The publisher will emit on the **main** thread. /// /// The request to the Cloud Functions backend made by this method automatically includes a - /// Firebase Instance ID token to identify the app instance. If a user is logged in with Firebase + /// Firebase Instance ID token to identify the app instance. If a user is logged in with + /// Firebase /// Auth, an auth ID token for the user is also automatically included. /// - /// Firebase Installations ID sends data to the Firebase backend periodically to collect information + /// Firebase Installations ID sends data to the Firebase backend periodically to collect + /// information /// regarding the app instance. To stop this, see `[FIRInstallations delete]`. It /// resumes with a new Instance ID the next time you call this method. /// - /// - Returns: A publisher emitting a `HTTPSCallableResult` instance. The publisher will emit on the *main* thread. + /// - Returns: A publisher emitting a `HTTPSCallableResult` instance. The publisher will emit on + /// the *main* thread. @discardableResult func call() -> Future { Future { promise in @@ -60,7 +63,8 @@ /// - `Dictionary`, where the contained objects are also one of these types. /// /// The request to the Cloud Functions backend made by this method automatically includes a - /// Firebase Instance ID token to identify the app instance. If a user is logged in with Firebase + /// Firebase Instance ID token to identify the app instance. If a user is logged in with + /// Firebase /// Auth, an auth ID token for the user is also automatically included. /// /// Firebase Instance ID sends data to the Firebase backend periodically to collect information @@ -68,7 +72,8 @@ /// resumes with a new Instance ID the next time you call this method. /// /// - Parameter data: The data passed into the Callable Function. - /// - Returns: A publisher emitting a `HTTPSCallableResult` instance. The publisher will emit on the *main* thread. + /// - Returns: A publisher emitting a `HTTPSCallableResult` instance. The publisher will emit on + /// the *main* thread. @discardableResult func call(_ data: Any?) -> Future { Future { promise in diff --git a/FirebaseCombineSwift/Sources/Storage/StorageReference+Combine.swift b/FirebaseCombineSwift/Sources/Storage/StorageReference+Combine.swift index 87026ea1b2c..32465f5adaa 100644 --- a/FirebaseCombineSwift/Sources/Storage/StorageReference+Combine.swift +++ b/FirebaseCombineSwift/Sources/Storage/StorageReference+Combine.swift @@ -32,7 +32,8 @@ /// - uploadData: The Data to upload. /// - metadata: metadata `StorageMetadata` containing additional information (MIME type, etc.) /// - /// - Returns: A publisher emitting a `StorageMetadata` instance. The publisher will emit on the *main* thread. + /// - Returns: A publisher emitting a `StorageMetadata` instance. The publisher will emit on the + /// *main* thread. @discardableResult func putData(_ data: Data, metadata: StorageMetadata? = nil) -> Future { @@ -54,9 +55,11 @@ /// /// - Parameters: /// - fileURL: A `URL` representing the system file path of the object to be uploaded. - /// - metadata: `StorageMetadata` containing additional information (MIME type, etc.) about the object being uploaded. + /// - metadata: `StorageMetadata` containing additional information (MIME type, etc.) about + /// the object being uploaded. /// - /// - Returns: A publisher emitting a `StorageMetadata` instance. The publisher will emit on the *main* thread. + /// - Returns: A publisher emitting a `StorageMetadata` instance. The publisher will emit on the + /// *main* thread. @discardableResult func putFile(from fileURL: URL, metadata: StorageMetadata? = nil) @@ -76,8 +79,10 @@ // MARK: - Downloads /// Asynchronously downloads the object at the `StorageReference` to an `Data` object in memory. - /// An `Data` of the provided max size will be allocated, so ensure that the device has enough free - /// memory to complete the download. For downloading large files, `writeToFile` may be a better option. + /// An `Data` of the provided max size will be allocated, so ensure that the device has enough + /// free + /// memory to complete the download. For downloading large files, `writeToFile` may be a better + /// option. /// /// The publisher will emit events on the **main** thread. /// @@ -85,7 +90,8 @@ /// - size: The maximum size in bytes to download. If the download exceeds this size, /// the task will be cancelled and an error will be returned. /// - /// - Returns: A publisher emitting a `Data` instance. The publisher will emit on the *main* thread. + /// - Returns: A publisher emitting a `Data` instance. The publisher will emit on the *main* + /// thread. @discardableResult func getData(maxSize size: Int64) -> Future { var task: StorageDownloadTask? @@ -129,7 +135,8 @@ /// /// The publisher will emit events on the **main** thread. /// - /// - Returns: A publisher emitting a `URL` instance. The publisher will emit on the *main* thread. + /// - Returns: A publisher emitting a `URL` instance. The publisher will emit on the *main* + /// thread. @discardableResult func downloadURL() -> Future { Future { promise in @@ -152,7 +159,8 @@ /// - Remark: /// `listAll` is only available for projects using Firebase Rules Version 2. /// - /// - Returns: A publisher emitting a `StorageListResult` instance. The publisher will emit on the *main* thread. + /// - Returns: A publisher emitting a `StorageListResult` instance. The publisher will emit on + /// the *main* thread. @discardableResult func listAll() -> Future { Future { promise in @@ -164,8 +172,10 @@ /// List up to `maxResults` items (files) and prefixes (folders) under this `StorageReference`. /// - /// Note that "/" is treated as a path delimiter. Firebase Storage does not support unsupported object - /// paths that end with "/" or contain two consecutive "/"s. All invalid objects in Firebase Storage will be + /// Note that "/" is treated as a path delimiter. Firebase Storage does not support unsupported + /// object + /// paths that end with "/" or contain two consecutive "/"s. All invalid objects in Firebase + /// Storage will be /// filtered. /// /// The publisher will emit events on the **main** thread. @@ -177,7 +187,8 @@ /// - Remark: /// `list(maxResults:)` is only available for projects using Firebase Rules Version 2. /// - /// - Returns: A publisher emitting a `StorageListResult` instance. The publisher will emit on the *main* thread. + /// - Returns: A publisher emitting a `StorageListResult` instance. The publisher will emit on + /// the *main* thread. @discardableResult func list(maxResults: Int64) -> Future { Future { promise in @@ -190,8 +201,10 @@ /// Resumes a previous call to `list(maxResults:)`, starting after a pagination token. /// Returns the next set of items (files) and prefixes (folders) under this `StorageReference. /// - /// Note that "/" is treated as a path delimiter. Firebase Storage does not support unsupported object - /// paths that end with "/" or contain two consecutive "/"s. All invalid objects in Firebase Storage + /// Note that "/" is treated as a path delimiter. Firebase Storage does not support unsupported + /// object + /// paths that end with "/" or contain two consecutive "/"s. All invalid objects in Firebase + /// Storage /// will be filtered out. /// /// The publisher will emit events on the **main** thread. @@ -202,9 +215,11 @@ /// - pageToken: A page token from a previous call to list. /// /// - Remark: - /// `list(maxResults:pageToken:)` is only available for projects using Firebase Rules Version 2. + /// `list(maxResults:pageToken:)` is only available for projects using Firebase Rules Version + /// 2. /// - /// - Returns: A publisher emitting a `StorageListResult` instance. The publisher will emit on the *main* thread. + /// - Returns: A publisher emitting a `StorageListResult` instance. The publisher will emit on + /// the *main* thread. @discardableResult func list(maxResults: Int64, pageToken: String) -> Future { Future { promise in @@ -220,7 +235,8 @@ /// /// The publisher will emit events on the **main** thread. /// - /// - Returns: A publisher emitting a `StorageMetadata` instance. The publisher will emit on the *main* thread. + /// - Returns: A publisher emitting a `StorageMetadata` instance. The publisher will emit on the + /// *main* thread. @discardableResult func getMetadata() -> Future { Future { promise in @@ -237,7 +253,8 @@ /// - Parameters: /// - metadata: A `StorageMetadata` object with the metadata to update. /// - /// - Returns: A publisher emitting a `StorageMetadata` instance. The publisher will emit on the *main* thread. + /// - Returns: A publisher emitting a `StorageMetadata` instance. The publisher will emit on the + /// *main* thread. @discardableResult func updateMetadata(_ metadata: StorageMetadata) -> Future { Future { promise in @@ -253,7 +270,8 @@ /// /// The publisher will emit events on the **main** thread. /// - /// - Returns: A publisher that emits whether the call was successful or not. The publisher will emit on the *main* thread. + /// - Returns: A publisher that emits whether the call was successful or not. The publisher will + /// emit on the *main* thread. @discardableResult func delete() -> Future { Future { promise in diff --git a/FirebaseCombineSwift/Tests/Integration/Storage/StorageIntegration.swift b/FirebaseCombineSwift/Tests/Integration/Storage/StorageIntegration.swift index efa223a33a0..526e1149802 100644 --- a/FirebaseCombineSwift/Tests/Integration/Storage/StorageIntegration.swift +++ b/FirebaseCombineSwift/Tests/Integration/Storage/StorageIntegration.swift @@ -84,7 +84,7 @@ class StorageIntegration: XCTestCase { let bundle = Bundle(for: StorageIntegration.self) let filePath = try XCTUnwrap(bundle.path(forResource: "1mb", ofType: "dat"), "Failed to get filePath") - let data = try XCTUnwrap(try Data(contentsOf: URL(fileURLWithPath: filePath)), + let data = try XCTUnwrap(Data(contentsOf: URL(fileURLWithPath: filePath)), "Failed to load file") for file in largeFiles + emptyFiles { diff --git a/FirebaseCombineSwift/Tests/Unit/Auth/GameCenterAuthProviderTests.swift b/FirebaseCombineSwift/Tests/Unit/Auth/GameCenterAuthProviderTests.swift index 71510d8d63c..34b5c64e8be 100644 --- a/FirebaseCombineSwift/Tests/Unit/Auth/GameCenterAuthProviderTests.swift +++ b/FirebaseCombineSwift/Tests/Unit/Auth/GameCenterAuthProviderTests.swift @@ -56,7 +56,7 @@ class GameCenterAuthProviderTests: XCTestCase { override func generateIdentityVerificationSignature(completionHandler: ((URL?, Data?, Data?, UInt64, Error?) -> Void)? = - nil) { + nil) { let url = URL(string: GameCenterAuthProviderTests.publicKeyURL) let signature = Data(base64Encoded: GameCenterAuthProviderTests.signature) let salt = Data(base64Encoded: GameCenterAuthProviderTests.salt) diff --git a/FirebaseCore/Internal/Sources/HeartbeatLogging/Heartbeat.swift b/FirebaseCore/Internal/Sources/HeartbeatLogging/Heartbeat.swift index ea92f6f19e0..aa265ed5f2f 100644 --- a/FirebaseCore/Internal/Sources/HeartbeatLogging/Heartbeat.swift +++ b/FirebaseCore/Internal/Sources/HeartbeatLogging/Heartbeat.swift @@ -43,8 +43,10 @@ struct Heartbeat: Codable, Equatable { /// An array of `TimePeriod`s that the heartbeat is tagged with. See `TimePeriod`. /// /// Heartbeats represent anonymous data points that measure SDK usage in moving averages for - /// various time periods. Because a single heartbeat can help calculate moving averages for multiple - /// time periods, this property serves to capture all the time periods that the heartbeat can represent in + /// various time periods. Because a single heartbeat can help calculate moving averages for + /// multiple + /// time periods, this property serves to capture all the time periods that the heartbeat can + /// represent in /// a moving average. let timePeriods: [TimePeriod] diff --git a/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatController.swift b/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatController.swift index fa3bb231dc9..20a021db4a1 100644 --- a/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatController.swift +++ b/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatController.swift @@ -36,7 +36,8 @@ public final class HeartbeatController { self.init(id: id, dateProvider: Date.init) } - /// Convenience initializer. Mirrors the semantics of the public initializer with the added benefit of + /// Convenience initializer. Mirrors the semantics of the public initializer with the added + /// benefit of /// injecting a custom date provider for improved testability. /// - Parameters: /// - id: The id to associate this controller's heartbeat storage with. @@ -59,7 +60,8 @@ public final class HeartbeatController { /// Asynchronously logs a new heartbeat, if needed. /// /// - Note: This API is thread-safe. - /// - Parameter agent: The string agent (i.e. Firebase User Agent) to associate the logged heartbeat with. + /// - Parameter agent: The string agent (i.e. Firebase User Agent) to associate the logged + /// heartbeat with. public func log(_ agent: String) { let date = dateProvider() diff --git a/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatStorage.swift b/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatStorage.swift index 742bcb52885..41572a0dc44 100644 --- a/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatStorage.swift +++ b/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatStorage.swift @@ -69,7 +69,8 @@ final class HeartbeatStorage: HeartbeatStorageProtocol { /// Makes a `HeartbeatStorage` instance using a given `String` identifier. /// /// The created persistent storage object is platform dependent. For tvOS, user defaults - /// is used as the underlying storage container due to system storage limits. For all other platforms, + /// is used as the underlying storage container due to system storage limits. For all other + /// platforms, /// the file system is used. /// /// - Parameter id: A `String` identifier used to create the `HeartbeatStorage`. @@ -115,7 +116,8 @@ final class HeartbeatStorage: HeartbeatStorageProtocol { /// Synchronously gets the current heartbeat data from storage and resets the storage using the /// given transform block. /// - /// This API is like any `getAndSet`-style API in that it gets (and returns) the current value and uses + /// This API is like any `getAndSet`-style API in that it gets (and returns) the current value and + /// uses /// a block to transform the current value (or, soon-to-be old value) to a new value. /// /// - Parameter transform: An optional block used to reset the currently stored heartbeat. diff --git a/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatsBundle.swift b/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatsBundle.swift index ef84f7cc714..a7db6a5e900 100644 --- a/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatsBundle.swift +++ b/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatsBundle.swift @@ -19,21 +19,25 @@ protocol HeartbeatsPayloadConvertible { func makeHeartbeatsPayload() -> HeartbeatsPayload } -/// A codable collection of heartbeats that has a fixed capacity and optimizations for storing heartbeats of +/// A codable collection of heartbeats that has a fixed capacity and optimizations for storing +/// heartbeats of /// multiple time periods. struct HeartbeatsBundle: Codable, HeartbeatsPayloadConvertible { /// The maximum number of heartbeats that can be stored in the buffer. let capacity: Int /// A cache used for keeping track of the last heartbeat date recorded for a given time period. /// - /// The cache contains the last added date for each time period. The reason only the date is cached is - /// because it's the only piece of information that should be used by clients to determine whether or not + /// The cache contains the last added date for each time period. The reason only the date is + /// cached is + /// because it's the only piece of information that should be used by clients to determine whether + /// or not /// to append a new heartbeat. private(set) var lastAddedHeartbeatDates: [TimePeriod: Date] /// A ring buffer of heartbeats. private var buffer: RingBuffer - /// A default cache provider that provides a dictionary of all time periods mapping to a default date. + /// A default cache provider that provides a dictionary of all time periods mapping to a default + /// date. static var cacheProvider: () -> [TimePeriod: Date] { let timePeriodsAndDates = TimePeriod.allCases.map { ($0, Date.distantPast) } return { Dictionary(uniqueKeysWithValues: timePeriodsAndDates) } diff --git a/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatsPayload.swift b/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatsPayload.swift index 72dbe3b3058..9a7d9e2796b 100644 --- a/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatsPayload.swift +++ b/FirebaseCore/Internal/Sources/HeartbeatLogging/HeartbeatsPayload.swift @@ -45,7 +45,8 @@ public protocol HTTPHeaderRepresentable { /// } /// public struct HeartbeatsPayload: Codable { - /// The version of the payload. See go/firebase-apple-heartbeats for details regarding current version. + /// The version of the payload. See go/firebase-apple-heartbeats for details regarding current + /// version. static let version: Int = 2 /// A payload component composed of a user agent and array of dates (heartbeats). diff --git a/FirebaseCore/Internal/Sources/HeartbeatLogging/RingBuffer.swift b/FirebaseCore/Internal/Sources/HeartbeatLogging/RingBuffer.swift index 2b9565ce264..6ba8c339733 100644 --- a/FirebaseCore/Internal/Sources/HeartbeatLogging/RingBuffer.swift +++ b/FirebaseCore/Internal/Sources/HeartbeatLogging/RingBuffer.swift @@ -41,7 +41,8 @@ struct RingBuffer: Sequence { tailIndex = circularQueue.startIndex } - /// Pushes an element to the back of the buffer, returning the element (`Element?`) that was overwritten. + /// Pushes an element to the back of the buffer, returning the element (`Element?`) that was + /// overwritten. /// - Parameter element: The element to push to the back of the buffer. /// - Returns: The element that was overwritten or `nil` if nothing was overwritten. /// - Complexity: O(1) @@ -72,7 +73,8 @@ struct RingBuffer: Sequence { return replaced } - /// Pops an element from the back of the buffer, returning the element (`Element?`) that was popped. + /// Pops an element from the back of the buffer, returning the element (`Element?`) that was + /// popped. /// - Returns: The element that was popped or `nil` if there was no element to pop. /// - Complexity: O(1) @discardableResult diff --git a/FirebaseCore/Internal/Sources/HeartbeatLogging/Storage.swift b/FirebaseCore/Internal/Sources/HeartbeatLogging/Storage.swift index 2b2959cd8cf..79cf1274b43 100644 --- a/FirebaseCore/Internal/Sources/HeartbeatLogging/Storage.swift +++ b/FirebaseCore/Internal/Sources/HeartbeatLogging/Storage.swift @@ -53,7 +53,8 @@ final class FileStorage: Storage { /// Reads and returns the data from this object's associated file resource. /// /// - Returns: The data stored on disk. - /// - Throws: An error if reading the contents of the file resource fails (i.e. file doesn't exist). + /// - Throws: An error if reading the contents of the file resource fails (i.e. file doesn't + /// exist). func read() throws -> Data { do { return try Data(contentsOf: url) diff --git a/FirebaseCore/Internal/Sources/HeartbeatLogging/_ObjC_HeartbeatController.swift b/FirebaseCore/Internal/Sources/HeartbeatLogging/_ObjC_HeartbeatController.swift index a00c28337ec..50cd24726ce 100644 --- a/FirebaseCore/Internal/Sources/HeartbeatLogging/_ObjC_HeartbeatController.swift +++ b/FirebaseCore/Internal/Sources/HeartbeatLogging/_ObjC_HeartbeatController.swift @@ -30,7 +30,8 @@ public class _ObjC_HeartbeatController: NSObject { /// Asynchronously logs a new heartbeat, if needed. /// /// - Note: This API is thread-safe. - /// - Parameter agent: The string agent (i.e. Firebase User Agent) to associate the logged heartbeat with. + /// - Parameter agent: The string agent (i.e. Firebase User Agent) to associate the logged + /// heartbeat with. public func log(_ agent: String) { heartbeatController.log(agent) } diff --git a/FirebaseCore/Internal/Sources/HeartbeatLogging/_ObjC_HeartbeatsPayload.swift b/FirebaseCore/Internal/Sources/HeartbeatLogging/_ObjC_HeartbeatsPayload.swift index fdf00edd5b0..83d72a2b924 100644 --- a/FirebaseCore/Internal/Sources/HeartbeatLogging/_ObjC_HeartbeatsPayload.swift +++ b/FirebaseCore/Internal/Sources/HeartbeatLogging/_ObjC_HeartbeatsPayload.swift @@ -14,7 +14,8 @@ import Foundation -/// A model object representing a payload of heartbeat data intended for sending in network requests. +/// A model object representing a payload of heartbeat data intended for sending in network +/// requests. @objc(FIRHeartbeatsPayload) public class _ObjC_HeartbeatsPayload: NSObject, HTTPHeaderRepresentable { /// The underlying Swift structure. diff --git a/FirebaseFunctions/Sources/Callable+Codable.swift b/FirebaseFunctions/Sources/Callable+Codable.swift index 5030fb32075..42c17fc16bb 100644 --- a/FirebaseFunctions/Sources/Callable+Codable.swift +++ b/FirebaseFunctions/Sources/Callable+Codable.swift @@ -49,7 +49,8 @@ public struct Callable { /// FCM token to identify the app instance. If a user is logged in with Firebase /// Auth, an auth ID token for the user is also automatically included. /// - /// Firebase Cloud Messaging sends data to the Firebase backend periodically to collect information + /// Firebase Cloud Messaging sends data to the Firebase backend periodically to collect + /// information /// regarding the app instance. To stop this, see `Messaging.deleteData()`. It /// resumes with a new FCM Token the next time you call this method. /// @@ -93,7 +94,8 @@ public struct Callable { /// ``` /// You can also call a HTTPS Callable function using the following syntax: /// ```swift - /// let greeter: Callable = functions.httpsCallable("greeter") + /// let greeter: Callable = + /// functions.httpsCallable("greeter") /// greeter(data) { result in /// print(result.greeting) /// } @@ -116,7 +118,8 @@ public struct Callable { /// FCM token to identify the app instance. If a user is logged in with Firebase /// Auth, an auth ID token for the user is also automatically included. /// - /// Firebase Cloud Messaging sends data to the Firebase backend periodically to collect information + /// Firebase Cloud Messaging sends data to the Firebase backend periodically to collect + /// information /// regarding the app instance. To stop this, see `Messaging.deleteData()`. It /// resumes with a new FCM Token the next time you call this method. /// @@ -145,7 +148,8 @@ public struct Callable { /// ``` /// You can also call a HTTPS Callable function using the following syntax: /// ```swift - /// let greeter: Callable = functions.httpsCallable("greeter") + /// let greeter: Callable = + /// functions.httpsCallable("greeter") /// let result = try await greeter(data) /// print(result.greeting) /// ``` diff --git a/FirebaseFunctions/Sources/Functions.swift b/FirebaseFunctions/Sources/Functions.swift index 6ab05324cb3..deb752fa37e 100644 --- a/FirebaseFunctions/Sources/Functions.swift +++ b/FirebaseFunctions/Sources/Functions.swift @@ -142,7 +142,8 @@ internal enum FunctionsConstants { return HTTPSCallable(functions: self, name: name) } - /// Creates a reference to the Callable HTTPS trigger with the given name and configuration options. + /// Creates a reference to the Callable HTTPS trigger with the given name and configuration + /// options. /// - Parameters: /// - name: The name of the Callable HTTPS trigger. /// - options: The options with which to customize the Callable HTTPS trigger. @@ -160,7 +161,8 @@ internal enum FunctionsConstants { return HTTPSCallable(functions: self, url: url) } - /// Creates a reference to the Callable HTTPS trigger with the given name and configuration options. + /// Creates a reference to the Callable HTTPS trigger with the given name and configuration + /// options. /// - Parameters: /// - url: The URL of the Callable HTTPS trigger. /// - options: The options with which to customize the Callable HTTPS trigger. @@ -171,7 +173,8 @@ internal enum FunctionsConstants { return HTTPSCallable(functions: self, url: url, options: options) } - /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an `Encodable` + /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an + /// `Encodable` /// request and the type of a `Decodable` response. /// - Parameters: /// - name: The name of the Callable HTTPS trigger @@ -179,7 +182,8 @@ internal enum FunctionsConstants { /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable` /// - encoder: The encoder instance to use to perform encoding. /// - decoder: The decoder instance to use to perform decoding. - /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud Functions invocations. + /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud + /// Functions invocations. open func httpsCallable(_ name: String, requestAs: Request.Type = Request.self, @@ -196,7 +200,8 @@ internal enum FunctionsConstants { ) } - /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an `Encodable` + /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an + /// `Encodable` /// request and the type of a `Decodable` response. /// - Parameters: /// - name: The name of the Callable HTTPS trigger @@ -205,7 +210,8 @@ internal enum FunctionsConstants { /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable` /// - encoder: The encoder instance to use to perform encoding. /// - decoder: The decoder instance to use to perform decoding. - /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud Functions invocations. + /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud + /// Functions invocations. open func httpsCallable(_ name: String, options: HTTPSCallableOptions, @@ -223,7 +229,8 @@ internal enum FunctionsConstants { ) } - /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an `Encodable` + /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an + /// `Encodable` /// request and the type of a `Decodable` response. /// - Parameters: /// - url: The url of the Callable HTTPS trigger @@ -231,7 +238,8 @@ internal enum FunctionsConstants { /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable` /// - encoder: The encoder instance to use to perform encoding. /// - decoder: The decoder instance to use to perform decoding. - /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud Functions invocations. + /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud + /// Functions invocations. open func httpsCallable(_ url: URL, requestAs: Request.Type = Request.self, @@ -248,7 +256,8 @@ internal enum FunctionsConstants { ) } - /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an `Encodable` + /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an + /// `Encodable` /// request and the type of a `Decodable` response. /// - Parameters: /// - url: The url of the Callable HTTPS trigger @@ -257,7 +266,8 @@ internal enum FunctionsConstants { /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable` /// - encoder: The encoder instance to use to perform encoding. /// - decoder: The decoder instance to use to perform decoding. - /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud Functions invocations. + /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud + /// Functions invocations. open func httpsCallable(_ url: URL, options: HTTPSCallableOptions, @@ -291,7 +301,8 @@ internal enum FunctionsConstants { // MARK: - Private Funcs (or Internal for tests) /// Solely used to have one precondition and one location where we fetch from the container. This - /// previously was avoided due to default arguments but that doesn't work well with Obj-C compatibility. + /// previously was avoided due to default arguments but that doesn't work well with Obj-C + /// compatibility. private class func functions(app: FirebaseApp?, region: String, customDomain: String?) -> Functions { precondition(app != nil, diff --git a/FirebaseFunctions/Tests/Integration/IntegrationTests.swift b/FirebaseFunctions/Tests/Integration/IntegrationTests.swift index 089eafd926d..c4fcda43d07 100644 --- a/FirebaseFunctions/Tests/Integration/IntegrationTests.swift +++ b/FirebaseFunctions/Tests/Integration/IntegrationTests.swift @@ -19,11 +19,15 @@ import FirebaseAuthInterop import FirebaseMessagingInterop import XCTest -/// This file was intitialized as a direct port of `FirebaseFunctionsSwift/Tests/IntegrationTests.swift` -/// which itself was ported from the Objective-C `FirebaseFunctions/Tests/Integration/FIRIntegrationTests.m` +/// This file was intitialized as a direct port of +/// `FirebaseFunctionsSwift/Tests/IntegrationTests.swift` +/// which itself was ported from the Objective-C +/// `FirebaseFunctions/Tests/Integration/FIRIntegrationTests.m` /// -/// The tests require the emulator to be running with `FirebaseFunctions/Backend/start.sh synchronous` -/// The Firebase Functions called in the tests are implemented in `FirebaseFunctions/Backend/index.js`. +/// The tests require the emulator to be running with `FirebaseFunctions/Backend/start.sh +/// synchronous` +/// The Firebase Functions called in the tests are implemented in +/// `FirebaseFunctions/Backend/index.js`. struct DataTestRequest: Encodable { var bool: Bool diff --git a/FirebaseFunctions/Tests/Unit/SerializerTests.swift b/FirebaseFunctions/Tests/Unit/SerializerTests.swift index 0685e52d522..6aaf1e9b947 100644 --- a/FirebaseFunctions/Tests/Unit/SerializerTests.swift +++ b/FirebaseFunctions/Tests/Unit/SerializerTests.swift @@ -46,7 +46,7 @@ class SerializerTests: XCTestCase { func testEncodeInt() throws { let serializer = FUNSerializer() let one = NSNumber(1) - let dict = try XCTUnwrap(try serializer.encode(one) as? NSDictionary) + let dict = try XCTUnwrap(serializer.encode(one) as? NSDictionary) XCTAssertEqual("type.googleapis.com/google.protobuf.Int64Value", dict["@type"] as? String) XCTAssertEqual("1", dict["value"] as? String) } @@ -73,7 +73,7 @@ class SerializerTests: XCTestCase { func testEncodeLong() throws { let serializer = FUNSerializer() let lowLong = NSNumber(-9_223_372_036_854_775_800) - let dict = try XCTUnwrap(try serializer.encode(lowLong) as? NSDictionary) + let dict = try XCTUnwrap(serializer.encode(lowLong) as? NSDictionary) XCTAssertEqual("type.googleapis.com/google.protobuf.Int64Value", dict["@type"] as? String) XCTAssertEqual("-9223372036854775800", dict["value"] as? String) } diff --git a/FirebaseInAppMessaging/Swift/Source/CustomInAppMessageDisplayViewModifier.swift b/FirebaseInAppMessaging/Swift/Source/CustomInAppMessageDisplayViewModifier.swift index 0e76bc538db..47da74a9630 100644 --- a/FirebaseInAppMessaging/Swift/Source/CustomInAppMessageDisplayViewModifier.swift +++ b/FirebaseInAppMessaging/Swift/Source/CustomInAppMessageDisplayViewModifier.swift @@ -44,7 +44,8 @@ struct ImageOnlyInAppMessageDisplayViewModifier: ViewModif @available(iOSApplicationExtension, unavailable) @available(tvOSApplicationExtension, unavailable) public extension View { - /// Overrides the default display of an image only in-app message as defined on the Firebase console. + /// Overrides the default display of an image only in-app message as defined on the Firebase + /// console. func imageOnlyInAppMessage(closure: @escaping (InAppMessagingImageOnlyDisplay, InAppMessagingDisplayDelegate) -> Content) diff --git a/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/FiamDisplaySwiftExample/AppDelegate.swift b/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/FiamDisplaySwiftExample/AppDelegate.swift index 65bb04593d7..0595fad663f 100644 --- a/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/FiamDisplaySwiftExample/AppDelegate.swift +++ b/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/FiamDisplaySwiftExample/AppDelegate.swift @@ -27,24 +27,33 @@ class AppDelegate: UIResponder, UIApplicationDelegate { } func applicationWillResignActive(_ application: UIApplication) { - // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. + // Sent when the application is about to move from active to inactive state. This can occur for + // certain types of temporary interruptions (such as an incoming phone call or SMS message) or + // when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering + // callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { - // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + // Use this method to release shared resources, save user data, invalidate timers, and store + // enough application state information to restore your application to its current state in case + // it is terminated later. + // If your application supports background execution, this method is called instead of + // applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { - // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. + // Called as part of the transition from the background to the active state; here you can undo + // many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { - // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + // Restart any tasks that were paused (or not yet started) while the application was inactive. + // If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { - // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + // Called when the application is about to terminate. Save data if appropriate. See also + // applicationDidEnterBackground:. } } diff --git a/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/InAppMessagingDisplay-UITests/InAppMessagingDisplayBannerViewUITests.swift b/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/InAppMessagingDisplay-UITests/InAppMessagingDisplayBannerViewUITests.swift index d21d5505456..a9b63070fa4 100644 --- a/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/InAppMessagingDisplay-UITests/InAppMessagingDisplayBannerViewUITests.swift +++ b/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/InAppMessagingDisplay-UITests/InAppMessagingDisplayBannerViewUITests.swift @@ -25,21 +25,25 @@ class InAppMessagingDisplayBannerViewUITests: InAppMessagingDisplayUITestsBase { override func setUp() { super.setUp() - // Put setup code here. This method is called before the invocation of each test method in the class. + // Put setup code here. This method is called before the invocation of each test method in the + // class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false - // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. + // UI tests must launch the application that they test. Doing this in setup will make sure it + // happens for each test method. XCUIApplication().launch() - // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. + // In UI tests it’s important to set the initial state - such as interface orientation - + // required for your tests before they run. The setUp method is a good place to do this. app = XCUIApplication() verificationLabel = app.staticTexts["verification-label-banner"] } override func tearDown() { - // Put teardown code here. This method is called after the invocation of each test method in the class. + // Put teardown code here. This method is called after the invocation of each test method in the + // class. super.tearDown() } diff --git a/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/InAppMessagingDisplay-UITests/InAppMessagingDisplayImageOnlyViewUITests.swift b/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/InAppMessagingDisplay-UITests/InAppMessagingDisplayImageOnlyViewUITests.swift index 075884f1eae..2d9382f5880 100644 --- a/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/InAppMessagingDisplay-UITests/InAppMessagingDisplayImageOnlyViewUITests.swift +++ b/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/InAppMessagingDisplay-UITests/InAppMessagingDisplayImageOnlyViewUITests.swift @@ -24,21 +24,25 @@ class InAppMessagingImageOnlyViewUITests: InAppMessagingDisplayUITestsBase { override func setUp() { super.setUp() - // Put setup code here. This method is called before the invocation of each test method in the class. + // Put setup code here. This method is called before the invocation of each test method in the + // class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false - // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. + // UI tests must launch the application that they test. Doing this in setup will make sure it + // happens for each test method. XCUIApplication().launch() - // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. + // In UI tests it’s important to set the initial state - such as interface orientation - + // required for your tests before they run. The setUp method is a good place to do this. app = XCUIApplication() verificationLabel = app.staticTexts["verification-label-image-only"] } override func tearDown() { - // Put teardown code here. This method is called after the invocation of each test method in the class. + // Put teardown code here. This method is called after the invocation of each test method in the + // class. super.tearDown() } diff --git a/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/InAppMessagingDisplay-UITests/InAppMessagingDisplayModalViewUITests.swift b/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/InAppMessagingDisplay-UITests/InAppMessagingDisplayModalViewUITests.swift index ed53f7aabaa..be3eec6d602 100644 --- a/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/InAppMessagingDisplay-UITests/InAppMessagingDisplayModalViewUITests.swift +++ b/FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/InAppMessagingDisplay-UITests/InAppMessagingDisplayModalViewUITests.swift @@ -22,21 +22,25 @@ class InAppMessagingDisplayModalViewUITests: InAppMessagingDisplayUITestsBase { override func setUp() { super.setUp() - // Put setup code here. This method is called before the invocation of each test method in the class. + // Put setup code here. This method is called before the invocation of each test method in the + // class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false - // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. + // UI tests must launch the application that they test. Doing this in setup will make sure it + // happens for each test method. XCUIApplication().launch() app = XCUIApplication() verificationLabel = app.staticTexts["verification-label-modal"] - // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. + // In UI tests it’s important to set the initial state - such as interface orientation - + // required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { - // Put teardown code here. This method is called after the invocation of each test method in the class. + // Put teardown code here. This method is called after the invocation of each test method in the + // class. super.tearDown() } diff --git a/FirebaseInAppMessaging/Tests/Integration/FunctionalTestApp/InAppMessaging_Example_iOS_SwiftUITests/InAppMessaging_Example_iOS_SwiftUITests.swift b/FirebaseInAppMessaging/Tests/Integration/FunctionalTestApp/InAppMessaging_Example_iOS_SwiftUITests/InAppMessaging_Example_iOS_SwiftUITests.swift index 5be73f9035c..8669aa069ac 100644 --- a/FirebaseInAppMessaging/Tests/Integration/FunctionalTestApp/InAppMessaging_Example_iOS_SwiftUITests/InAppMessaging_Example_iOS_SwiftUITests.swift +++ b/FirebaseInAppMessaging/Tests/Integration/FunctionalTestApp/InAppMessaging_Example_iOS_SwiftUITests/InAppMessaging_Example_iOS_SwiftUITests.swift @@ -26,7 +26,8 @@ class InAppMessaging_Example_iOS_SwiftUITests: XCTestCase { } override func tearDown() { - // Put teardown code here. This method is called after the invocation of each test method in the class. + // Put teardown code here. This method is called after the invocation of each test method in the + // class. XCUIDevice.shared.orientation = .portrait super.tearDown() } diff --git a/FirebaseMLModelDownloader/Apps/Sample/MLDownloaderTestApp/AppDelegate.swift b/FirebaseMLModelDownloader/Apps/Sample/MLDownloaderTestApp/AppDelegate.swift index 695f08d1b5d..6e742c71e94 100644 --- a/FirebaseMLModelDownloader/Apps/Sample/MLDownloaderTestApp/AppDelegate.swift +++ b/FirebaseMLModelDownloader/Apps/Sample/MLDownloaderTestApp/AppDelegate.swift @@ -43,7 +43,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { // Called when the user discards a scene session. - // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. - // Use this method to release any resources that were specific to the discarded scenes, as they will not return. + // If any sessions were discarded while the application was not running, this will be called + // shortly after application:didFinishLaunchingWithOptions. + // Use this method to release any resources that were specific to the discarded scenes, as they + // will not return. } } diff --git a/FirebaseMLModelDownloader/Apps/Sample/MLDownloaderTestApp/SceneDelegate.swift b/FirebaseMLModelDownloader/Apps/Sample/MLDownloaderTestApp/SceneDelegate.swift index 1be8e397024..4e2a910ac72 100644 --- a/FirebaseMLModelDownloader/Apps/Sample/MLDownloaderTestApp/SceneDelegate.swift +++ b/FirebaseMLModelDownloader/Apps/Sample/MLDownloaderTestApp/SceneDelegate.swift @@ -20,9 +20,12 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. - // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. - // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). + // Use this method to optionally configure and attach the UIWindow `window` to the provided + // UIWindowScene `scene`. + // If using a storyboard, the `window` property will automatically be initialized and attached + // to the scene. + // This delegate does not imply the connecting scene or session are new (see + // `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() @@ -39,13 +42,16 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. - // Release any resources associated with this scene that can be re-created the next time the scene connects. - // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). + // Release any resources associated with this scene that can be re-created the next time the + // scene connects. + // The scene may re-connect later, as its session was not necessarily discarded (see + // `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. - // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. + // Use this method to restart any tasks that were paused (or not yet started) when the scene was + // inactive. } func sceneWillResignActive(_ scene: UIScene) { @@ -60,7 +66,8 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. - // Use this method to save data, release shared resources, and store enough scene-specific state information + // Use this method to save data, release shared resources, and store enough scene-specific state + // information // to restore the scene back to its current state. } } diff --git a/FirebaseMLModelDownloader/Sources/ModelDownloadConditions.swift b/FirebaseMLModelDownloader/Sources/ModelDownloadConditions.swift index c5cf39e854c..f3cca5b33d0 100644 --- a/FirebaseMLModelDownloader/Sources/ModelDownloadConditions.swift +++ b/FirebaseMLModelDownloader/Sources/ModelDownloadConditions.swift @@ -19,7 +19,8 @@ public struct ModelDownloadConditions { let allowsCellularAccess: Bool /// Conditions that need to be met to start a model file download. - /// - Parameter allowsCellularAccess: Allow model downloading on a cellular connection. Default is `true`. + /// - Parameter allowsCellularAccess: Allow model downloading on a cellular connection. Default is + /// `true`. public init(allowsCellularAccess: Bool = true) { self.allowsCellularAccess = allowsCellularAccess } diff --git a/FirebaseMLModelDownloader/Sources/ModelDownloader.swift b/FirebaseMLModelDownloader/Sources/ModelDownloader.swift index 6094ae02b9e..6bb44524cb6 100644 --- a/FirebaseMLModelDownloader/Sources/ModelDownloader.swift +++ b/FirebaseMLModelDownloader/Sources/ModelDownloader.swift @@ -18,11 +18,14 @@ import FirebaseInstallations /// Possible ways to get a custom model. public enum ModelDownloadType { - /// Get local model stored on device if available. If no local model on device, this is the same as `latestModel`. + /// Get local model stored on device if available. If no local model on device, this is the same + /// as `latestModel`. case localModel - /// Get local model on device if available and update to latest model from server in the background. If no local model on device, this is the same as `latestModel`. + /// Get local model on device if available and update to latest model from server in the + /// background. If no local model on device, this is the same as `latestModel`. case localModelUpdateInBackground - /// Get latest model from server. Does not make a network call for model file download if local model matches the latest version on server. + /// Get latest model from server. Does not make a network call for model file download if local + /// model matches the latest version on server. case latestModel } @@ -120,13 +123,16 @@ public class ModelDownloader { } } - /// Downloads a custom model to device or gets a custom model already on device, with an optional handler for progress. + /// Downloads a custom model to device or gets a custom model already on device, with an optional + /// handler for progress. /// - Parameters: /// - modelName: The name of the model, matching Firebase console. /// - downloadType: ModelDownloadType used to get the model. /// - conditions: Conditions needed to perform a model download. - /// - progressHandler: Optional. Returns a float in [0.0, 1.0] that can be used to monitor model download progress. - /// - completion: Returns either a `CustomModel` on success, or a `DownloadError` on failure, at the end of a model download. + /// - progressHandler: Optional. Returns a float in [0.0, 1.0] that can be used to monitor model + /// download progress. + /// - completion: Returns either a `CustomModel` on success, or a `DownloadError` on failure, at + /// the end of a model download. public func getModel(name modelName: String, downloadType: ModelDownloadType, conditions: ModelDownloadConditions, @@ -219,7 +225,8 @@ public class ModelDownloader { } /// Gets the set of all downloaded models saved on device. - /// - Parameter completion: Returns either a set of `CustomModel` models on success, or a `DownloadedModelError` on failure. + /// - Parameter completion: Returns either a set of `CustomModel` models on success, or a + /// `DownloadedModelError` on failure. public func listDownloadedModels(completion: @escaping (Result, DownloadedModelError>) -> Void) { do { @@ -279,14 +286,17 @@ public class ModelDownloader { } } - /// Deletes a custom model file from device as well as corresponding model information saved in UserDefaults. + /// Deletes a custom model file from device as well as corresponding model information saved in + /// UserDefaults. /// - Parameters: - /// - modelName: The name of the model, matching Firebase console and already downloaded to device. + /// - modelName: The name of the model, matching Firebase console and already downloaded to + /// device. /// - completion: Returns a `DownloadedModelError` on failure. public func deleteDownloadedModel(name modelName: String, completion: @escaping (Result) -> Void) { - // Ensure that there is a matching model file on device, with corresponding model information in UserDefaults. + // Ensure that there is a matching model file on device, with corresponding model information in + // UserDefaults. guard let modelURL = ModelFileManager.getDownloadedModelFileURL( appName: appName, modelName: modelName @@ -474,7 +484,8 @@ extension ModelDownloader { } } self.taskSerialQueue.sync { - // Merge duplicate requests if there is already a download in progress for the same model. + // Merge duplicate requests if there is already a download in progress for the same + // model. if let downloadTask = self.currentDownloadTask[modelName], downloadTask.canMergeRequests() { downloadTask.merge( @@ -507,7 +518,8 @@ extension ModelDownloader { /// Local model info is the latest model info. case .notModified: guard let localModel = self.getLocalModel(modelName: modelName) else { - // This can only happen if either local model info or the model file was wiped out after model info request but before server response. + // This can only happen if either local model info or the model file was wiped out after + // model info request but before server response. self .asyncOnMainQueue(completion(.failure(.internalError(description: ModelDownloader .ErrorDescription.deletedLocalModelInfoOrFile)))) @@ -557,7 +569,7 @@ public enum DownloadedModelError: Error { extension DownloadError { /// Model download URL expired before model download. // Model info retrieval and download is retried `numberOfRetries` times before failing. - static let expiredDownloadURL: DownloadError = DownloadError + static let expiredDownloadURL: DownloadError = .internalError(description: "Expired model download URL.") } diff --git a/FirebaseMLModelDownloader/Sources/ModelInfoRetriever.swift b/FirebaseMLModelDownloader/Sources/ModelInfoRetriever.swift index 85d80bf3b0a..b91258a55f3 100644 --- a/FirebaseMLModelDownloader/Sources/ModelInfoRetriever.swift +++ b/FirebaseMLModelDownloader/Sources/ModelInfoRetriever.swift @@ -371,7 +371,8 @@ class ModelInfoRetriever { .statusCode)) completion(.failure(.invalidArgument)) case 401, 403: - // Error could be due to FirebaseML API not enabled for project, or invalid permissions. + // Error could be due to FirebaseML API not enabled for project, or invalid + // permissions. let errorMessage = self.getErrorFromResponse(data) let description = errorMessage ?? ModelInfoRetriever.ErrorDescription.permissionDenied DeviceLogger.logEvent(level: .debug, diff --git a/FirebaseMessaging/Apps/AdvancedSample/NotificationServiceExtension/NotificationService.swift b/FirebaseMessaging/Apps/AdvancedSample/NotificationServiceExtension/NotificationService.swift index 099deeb5c71..d8adec06fbc 100644 --- a/FirebaseMessaging/Apps/AdvancedSample/NotificationServiceExtension/NotificationService.swift +++ b/FirebaseMessaging/Apps/AdvancedSample/NotificationServiceExtension/NotificationService.swift @@ -41,7 +41,8 @@ class NotificationService: UNNotificationServiceExtension { override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. - // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. + // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the + // original push payload will be used. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } diff --git a/FirebaseMessaging/Apps/AdvancedSample/SampleWatchWatchKitExtension/ComplicationController.swift b/FirebaseMessaging/Apps/AdvancedSample/SampleWatchWatchKitExtension/ComplicationController.swift index e93f3b0de0f..12990b7702b 100644 --- a/FirebaseMessaging/Apps/AdvancedSample/SampleWatchWatchKitExtension/ComplicationController.swift +++ b/FirebaseMessaging/Apps/AdvancedSample/SampleWatchWatchKitExtension/ComplicationController.swift @@ -39,7 +39,8 @@ class ComplicationController: NSObject, CLKComplicationDataSource { func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) { - // Call the handler with the last entry date you can currently provide or nil if you can't support future timelines + // Call the handler with the last entry date you can currently provide or nil if you can't + // support future timelines handler(nil) } diff --git a/FirebaseMessaging/Apps/Shared/ContentView.swift b/FirebaseMessaging/Apps/Shared/ContentView.swift index 3276dbf7b2f..df4e69eb055 100644 --- a/FirebaseMessaging/Apps/Shared/ContentView.swift +++ b/FirebaseMessaging/Apps/Shared/ContentView.swift @@ -43,7 +43,8 @@ struct ContentView: View { .fontWeight(.semibold) Text(identity.token ?? "None") .foregroundColor(.green) - // Increase the layout priority to allow more than one line to be shown. Without this, the + // Increase the layout priority to allow more than one line to be shown. Without this, + // the // simulator renders a single truncated line even though the Preview renders it // appropriately. Potentially a bug in the simulator? .layoutPriority(1) @@ -248,7 +249,8 @@ struct ContentView_Previews: PreviewProvider { var identity = Identity() identity.installationsID = UUID().uuidString - // The token is a long string, generate a very long repeating string of characters to see how the view + // The token is a long string, generate a very long repeating string of characters to see how + // the view // will react. let longString = UUID().uuidString.replacingOccurrences(of: "-", with: "") identity.token = Array(repeating: longString, count: 8).reduce("", +) diff --git a/FirebaseRemoteConfigSwift/Sources/PropertyWrapper/RemoteConfigProperty.swift b/FirebaseRemoteConfigSwift/Sources/PropertyWrapper/RemoteConfigProperty.swift index a181fd3369a..0df0e71bac8 100644 --- a/FirebaseRemoteConfigSwift/Sources/PropertyWrapper/RemoteConfigProperty.swift +++ b/FirebaseRemoteConfigSwift/Sources/PropertyWrapper/RemoteConfigProperty.swift @@ -33,7 +33,8 @@ public struct RemoteConfigProperty: DynamicProperty { /// Creates an instance by providing a config key. /// /// - Parameter key: key name - /// - Parameter fallback: The value to fall back to if the key doesn't exist in remote or default configs + /// - Parameter fallback: The value to fall back to if the key doesn't exist in remote or default + /// configs public init(key: String, fallback: T) { self.key = key diff --git a/FirebaseSessions/Sources/FirebaseSessions.swift b/FirebaseSessions/Sources/FirebaseSessions.swift index 82a0f40401f..9c8f7871f22 100644 --- a/FirebaseSessions/Sources/FirebaseSessions.swift +++ b/FirebaseSessions/Sources/FirebaseSessions.swift @@ -123,7 +123,8 @@ private enum GoogleDataTransportConfig { } } - // Initializes the SDK and begines the process of listening for lifecycle events and logging events + // Initializes the SDK and begines the process of listening for lifecycle events and logging + // events init(appID: String, sessionGenerator: SessionGenerator, coordinator: SessionCoordinatorProtocol, initiator: SessionInitiator, appInfo: ApplicationInfoProtocol, settings: SettingsProtocol, loggedEventCallback: @escaping (Result) -> Void) { diff --git a/FirebaseSessions/Sources/Settings/RemoteSettings.swift b/FirebaseSessions/Sources/Settings/RemoteSettings.swift index f31f9bfdb05..15dffb18e43 100644 --- a/FirebaseSessions/Sources/Settings/RemoteSettings.swift +++ b/FirebaseSessions/Sources/Settings/RemoteSettings.swift @@ -15,7 +15,8 @@ import Foundation -/// Extends ApplicationInfoProtocol to string-format a combined appDisplayVersion and appBuildVersion +/// Extends ApplicationInfoProtocol to string-format a combined appDisplayVersion and +/// appBuildVersion extension ApplicationInfoProtocol { var synthesizedVersion: String { return "\(appDisplayVersion) (\(appBuildVersion))" } } diff --git a/FirebaseSessions/Sources/Settings/SettingsCacheClient.swift b/FirebaseSessions/Sources/Settings/SettingsCacheClient.swift index 00bace8d60b..b743d958610 100644 --- a/FirebaseSessions/Sources/Settings/SettingsCacheClient.swift +++ b/FirebaseSessions/Sources/Settings/SettingsCacheClient.swift @@ -15,7 +15,8 @@ import Foundation -/// CacheKey is like a "key" to a "safe". It provides necessary metadata about the current cache to know if it should be expired. +/// CacheKey is like a "key" to a "safe". It provides necessary metadata about the current cache to +/// know if it should be expired. struct CacheKey: Codable { var createdAt: Date var googleAppID: String @@ -24,15 +25,20 @@ struct CacheKey: Codable { /// SettingsCacheClient is responsible for accessing the cache that Settings are stored in. protocol SettingsCacheClient { - /// Returns in-memory cache content in O(1) time. Returns empty dictionary if it does not exist in cache. + /// Returns in-memory cache content in O(1) time. Returns empty dictionary if it does not exist in + /// cache. var cacheContent: [String: Any] { get set } - /// Returns in-memory cache-key, no performance guarantee because type-casting depends on size of CacheKey + /// Returns in-memory cache-key, no performance guarantee because type-casting depends on size of + /// CacheKey var cacheKey: CacheKey? { get set } /// Removes all cache content and cache-key func removeCache() } -/// SettingsCache uses UserDefaults to store Settings on-disk, but also directly query UserDefaults when accessing Settings values during run-time. This is because UserDefaults encapsulates both in-memory and persisted-on-disk storage, allowing fast synchronous access in-app while hiding away the complexity of managing persistence asynchronously. +/// SettingsCache uses UserDefaults to store Settings on-disk, but also directly query UserDefaults +/// when accessing Settings values during run-time. This is because UserDefaults encapsulates both +/// in-memory and persisted-on-disk storage, allowing fast synchronous access in-app while hiding +/// away the complexity of managing persistence asynchronously. class SettingsCache: SettingsCacheClient { private static let settingsVersion: Int = 1 private enum UserDefaultsKeys { @@ -40,7 +46,8 @@ class SettingsCache: SettingsCacheClient { static let forCacheKey = "firebase-sessions-cache-key" } - /// UserDefaults holds values in memory, making access O(1) and synchronous within the app, while abstracting away async disk IO. + /// UserDefaults holds values in memory, making access O(1) and synchronous within the app, while + /// abstracting away async disk IO. private let cache: UserDefaults = .standard /// Converting to dictionary is O(1) because object conversion is O(1) @@ -67,7 +74,7 @@ class SettingsCache: SettingsCacheClient { } set { do { - cache.set(try JSONEncoder().encode(newValue), forKey: UserDefaultsKeys.forCacheKey) + try cache.set(JSONEncoder().encode(newValue), forKey: UserDefaultsKeys.forCacheKey) } catch { Logger.logError("[Settings] Encoding CacheKey failed with error: \(error)") } diff --git a/FirebaseSessions/Sources/Time.swift b/FirebaseSessions/Sources/Time.swift index 61c5f1540cc..24305e826f4 100644 --- a/FirebaseSessions/Sources/Time.swift +++ b/FirebaseSessions/Sources/Time.swift @@ -20,7 +20,8 @@ protocol TimeProvider { } /// -/// Time is provides timestamp values in different formats to classes in the Sessions SDK. It mainly exists for testing purposes. +/// Time is provides timestamp values in different formats to classes in the Sessions SDK. It mainly +/// exists for testing purposes. /// class Time: TimeProvider { // Returns the current time as a timestamp in microseconds diff --git a/FirebaseSessions/Tests/Unit/Library/FirebaseSessionsTestsBase.swift b/FirebaseSessions/Tests/Unit/Library/FirebaseSessionsTestsBase.swift index 1759ff3ea36..aab83d2f217 100644 --- a/FirebaseSessions/Tests/Unit/Library/FirebaseSessionsTestsBase.swift +++ b/FirebaseSessions/Tests/Unit/Library/FirebaseSessionsTestsBase.swift @@ -65,7 +65,8 @@ class FirebaseSessionsTestsBase: XCTestCase { /// It has 4 parts: /// - `subscriberSDKs` tells the test to expect the list of subscriber SDKs /// - `preSessionsInit` is before Sessions or any Subscriber SDKs start up. This is a good - /// place to mock variables in any dependencies (eg. Settings, or mocking any Subscribers themselves) + /// place to mock variables in any dependencies (eg. Settings, or mocking any Subscribers + /// themselves) /// - `postSessionsInit` is after Sessions has started up, but before logging any events. This /// is a good place for Subscribers to call register on the Sessions SDK /// - `postLogEvent` is called whenever an event is logged via the Sessions SDK. This is where diff --git a/FirebaseSessions/Tests/Unit/SessionStartEventTests.swift b/FirebaseSessions/Tests/Unit/SessionStartEventTests.swift index 1048d6b8791..07249e527a5 100644 --- a/FirebaseSessions/Tests/Unit/SessionStartEventTests.swift +++ b/FirebaseSessions/Tests/Unit/SessionStartEventTests.swift @@ -325,29 +325,27 @@ class SessionStartEventTests: XCTestCase { ), ] - expectations.forEach { ( - given: GULNetworkType, - expected: firebase_appquality_sessions_NetworkConnectionInfo_NetworkType - ) in - let mockNetworkInfo = MockNetworkInfo() - mockNetworkInfo.networkType = given - appInfo.networkInfo = mockNetworkInfo + expectations.forEach { (given: GULNetworkType, + expected: firebase_appquality_sessions_NetworkConnectionInfo_NetworkType) in + let mockNetworkInfo = MockNetworkInfo() + mockNetworkInfo.networkType = given + appInfo.networkInfo = mockNetworkInfo - let event = SessionStartEvent( - sessionInfo: self.defaultSessionInfo, - appInfo: appInfo, - time: time - ) + let event = SessionStartEvent( + sessionInfo: self.defaultSessionInfo, + appInfo: appInfo, + time: time + ) - // These fields will only be filled in when the Perf SDK is installed - event.set(subscriber: .Performance, isDataCollectionEnabled: true, appInfo: appInfo) + // These fields will only be filled in when the Perf SDK is installed + event.set(subscriber: .Performance, isDataCollectionEnabled: true, appInfo: appInfo) - testProtoAndDecodedProto(sessionEvent: event) { proto in - XCTAssertEqual( - event.proto.application_info.apple_app_info.network_connection_info.network_type, - expected - ) - } + testProtoAndDecodedProto(sessionEvent: event) { proto in + XCTAssertEqual( + event.proto.application_info.apple_app_info.network_connection_info.network_type, + expected + ) + } } } @@ -410,29 +408,28 @@ class SessionStartEventTests: XCTestCase { ] expectations - .forEach { ( - given: String, - expected: firebase_appquality_sessions_NetworkConnectionInfo_MobileSubtype - ) in - let mockNetworkInfo = MockNetworkInfo() - mockNetworkInfo.mobileSubtype = given - appInfo.networkInfo = mockNetworkInfo - - let event = SessionStartEvent( - sessionInfo: self.defaultSessionInfo, - appInfo: appInfo, - time: time - ) - - // These fields will only be filled in when the Perf SDK is installed - event.set(subscriber: .Performance, isDataCollectionEnabled: true, appInfo: appInfo) - - testProtoAndDecodedProto(sessionEvent: event) { proto in - XCTAssertEqual( - event.proto.application_info.apple_app_info.network_connection_info.mobile_subtype, - expected + .forEach { (given: String, + expected: firebase_appquality_sessions_NetworkConnectionInfo_MobileSubtype) in + let mockNetworkInfo = MockNetworkInfo() + mockNetworkInfo.mobileSubtype = given + appInfo.networkInfo = mockNetworkInfo + + let event = SessionStartEvent( + sessionInfo: self.defaultSessionInfo, + appInfo: appInfo, + time: time ) - } + + // These fields will only be filled in when the Perf SDK is installed + event.set(subscriber: .Performance, isDataCollectionEnabled: true, appInfo: appInfo) + + testProtoAndDecodedProto(sessionEvent: event) { proto in + XCTAssertEqual( + event.proto.application_info.apple_app_info.network_connection_info + .mobile_subtype, + expected + ) + } } } #endif // os(iOS) && !targetEnvironment(macCatalyst) && !os(xrOS) @@ -494,29 +491,28 @@ class SessionStartEventTests: XCTestCase { ] expectations - .forEach { ( - given: String, - expected: firebase_appquality_sessions_NetworkConnectionInfo_MobileSubtype - ) in - let mockNetworkInfo = MockNetworkInfo() - mockNetworkInfo.mobileSubtype = given - appInfo.networkInfo = mockNetworkInfo - - let event = SessionStartEvent( - sessionInfo: self.defaultSessionInfo, - appInfo: appInfo, - time: time - ) - - // These fields will only be filled in when the Perf SDK is installed - event.set(subscriber: .Performance, isDataCollectionEnabled: true, appInfo: appInfo) - - testProtoAndDecodedProto(sessionEvent: event) { proto in - XCTAssertEqual( - event.proto.application_info.apple_app_info.network_connection_info.mobile_subtype, - expected + .forEach { (given: String, + expected: firebase_appquality_sessions_NetworkConnectionInfo_MobileSubtype) in + let mockNetworkInfo = MockNetworkInfo() + mockNetworkInfo.mobileSubtype = given + appInfo.networkInfo = mockNetworkInfo + + let event = SessionStartEvent( + sessionInfo: self.defaultSessionInfo, + appInfo: appInfo, + time: time ) - } + + // These fields will only be filled in when the Perf SDK is installed + event.set(subscriber: .Performance, isDataCollectionEnabled: true, appInfo: appInfo) + + testProtoAndDecodedProto(sessionEvent: event) { proto in + XCTAssertEqual( + event.proto.application_info.apple_app_info.network_connection_info + .mobile_subtype, + expected + ) + } } } #endif // os(iOS) && !targetEnvironment(macCatalyst) @@ -589,29 +585,28 @@ class SessionStartEventTests: XCTestCase { ] expectations - .forEach { ( - given: String, - expected: firebase_appquality_sessions_NetworkConnectionInfo_MobileSubtype - ) in - let mockNetworkInfo = MockNetworkInfo() - mockNetworkInfo.mobileSubtype = given - appInfo.networkInfo = mockNetworkInfo - - let event = SessionStartEvent( - sessionInfo: self.defaultSessionInfo, - appInfo: appInfo, - time: time - ) - - // These fields will only be filled in when the Perf SDK is installed - event.set(subscriber: .Performance, isDataCollectionEnabled: true, appInfo: appInfo) - - testProtoAndDecodedProto(sessionEvent: event) { proto in - XCTAssertEqual( - event.proto.application_info.apple_app_info.network_connection_info.mobile_subtype, - expected + .forEach { (given: String, + expected: firebase_appquality_sessions_NetworkConnectionInfo_MobileSubtype) in + let mockNetworkInfo = MockNetworkInfo() + mockNetworkInfo.mobileSubtype = given + appInfo.networkInfo = mockNetworkInfo + + let event = SessionStartEvent( + sessionInfo: self.defaultSessionInfo, + appInfo: appInfo, + time: time ) - } + + // These fields will only be filled in when the Perf SDK is installed + event.set(subscriber: .Performance, isDataCollectionEnabled: true, appInfo: appInfo) + + testProtoAndDecodedProto(sessionEvent: event) { proto in + XCTAssertEqual( + event.proto.application_info.apple_app_info.network_connection_info + .mobile_subtype, + expected + ) + } } } #endif // os(iOS) && !targetEnvironment(macCatalyst) && !os(xrOS) @@ -682,29 +677,28 @@ class SessionStartEventTests: XCTestCase { ] expectations - .forEach { ( - given: String, - expected: firebase_appquality_sessions_NetworkConnectionInfo_MobileSubtype - ) in - let mockNetworkInfo = MockNetworkInfo() - mockNetworkInfo.mobileSubtype = given - appInfo.networkInfo = mockNetworkInfo - - let event = SessionStartEvent( - sessionInfo: self.defaultSessionInfo, - appInfo: appInfo, - time: time - ) - - // These fields will only be filled in when the Perf SDK is installed - event.set(subscriber: .Performance, isDataCollectionEnabled: true, appInfo: appInfo) - - testProtoAndDecodedProto(sessionEvent: event) { proto in - XCTAssertEqual( - event.proto.application_info.apple_app_info.network_connection_info.mobile_subtype, - expected + .forEach { (given: String, + expected: firebase_appquality_sessions_NetworkConnectionInfo_MobileSubtype) in + let mockNetworkInfo = MockNetworkInfo() + mockNetworkInfo.mobileSubtype = given + appInfo.networkInfo = mockNetworkInfo + + let event = SessionStartEvent( + sessionInfo: self.defaultSessionInfo, + appInfo: appInfo, + time: time ) - } + + // These fields will only be filled in when the Perf SDK is installed + event.set(subscriber: .Performance, isDataCollectionEnabled: true, appInfo: appInfo) + + testProtoAndDecodedProto(sessionEvent: event) { proto in + XCTAssertEqual( + event.proto.application_info.apple_app_info.network_connection_info + .mobile_subtype, + expected + ) + } } } #endif // os(iOS) && !targetEnvironment(macCatalyst) diff --git a/FirebaseSharedSwift/Sources/FirebaseRemoteConfigValueDecoding.swift b/FirebaseSharedSwift/Sources/FirebaseRemoteConfigValueDecoding.swift index 6d81d90e19a..39482c0b318 100644 --- a/FirebaseSharedSwift/Sources/FirebaseRemoteConfigValueDecoding.swift +++ b/FirebaseSharedSwift/Sources/FirebaseRemoteConfigValueDecoding.swift @@ -14,7 +14,8 @@ import Foundation -/// Conform to this protocol for the Firebase Decoder to extract values as from a RemoteConfigValue object. +/// Conform to this protocol for the Firebase Decoder to extract values as from a RemoteConfigValue +/// object. public protocol FirebaseRemoteConfigValueDecoding { func numberValue() -> NSNumber func boolValue() -> Bool diff --git a/FirebaseStorage/Sources/AsyncAwait.swift b/FirebaseStorage/Sources/AsyncAwait.swift index 54e9125ed2f..06fbc690090 100644 --- a/FirebaseStorage/Sources/AsyncAwait.swift +++ b/FirebaseStorage/Sources/AsyncAwait.swift @@ -44,7 +44,8 @@ import Foundation /// - uploadData: The Data to upload. /// - metadata: Optional StorageMetadata containing additional information (MIME type, etc.) /// about the object being uploaded. - /// - onProgress: An optional closure function to return a `Progress` instance while the upload proceeds. + /// - onProgress: An optional closure function to return a `Progress` instance while the + /// upload proceeds. /// - Throws: /// - An error if the operation failed, for example if Storage was unreachable. /// - Returns: StorageMetadata with additional information about the object being uploaded. @@ -81,9 +82,11 @@ import Foundation /// - url: A URL representing the system file path of the object to be uploaded. /// - metadata: Optional StorageMetadata containing additional information (MIME type, etc.) /// about the object being uploaded. - /// - onProgress: An optional closure function to return a `Progress` instance while the upload proceeds. + /// - onProgress: An optional closure function to return a `Progress` instance while the + /// upload proceeds. /// - Throws: - /// - An error if the operation failed, for example if no file was present at the specified `url`. + /// - An error if the operation failed, for example if no file was present at the specified + /// `url`. /// - Returns: `StorageMetadata` with additional information about the object being uploaded. func putFileAsync(from url: URL, metadata: StorageMetadata? = nil, @@ -115,7 +118,8 @@ import Foundation /// /// - Parameters: /// - fileUrl: A URL representing the system file path of the object to be uploaded. - /// - onProgress: An optional closure function to return a `Progress` instance while the download proceeds. + /// - onProgress: An optional closure function to return a `Progress` instance while the + /// download proceeds. /// - Throws: /// - An error if the operation failed, for example if Storage was unreachable /// or `fileURL` did not reference a valid path on disk. diff --git a/FirebaseStorage/Sources/Internal/StorageListTask.swift b/FirebaseStorage/Sources/Internal/StorageListTask.swift index 93e918a24f4..72d0f86b9c3 100644 --- a/FirebaseStorage/Sources/Internal/StorageListTask.swift +++ b/FirebaseStorage/Sources/Internal/StorageListTask.swift @@ -83,11 +83,13 @@ internal class StorageListTask: StorageTask, StorageTaskManagement { queryParams["prefix"] = "\(prefix)/" } - // Firebase Storage uses file system semantics and treats slashes as separators. GCS's List API + // Firebase Storage uses file system semantics and treats slashes as separators. GCS's List + // API // does not prescribe a separator, and hence we need to provide a slash as the delimiter. queryParams["delimiter"] = "/" - // listAll() doesn't set a pageSize as this allows Firebase Storage to determine how many items + // listAll() doesn't set a pageSize as this allows Firebase Storage to determine how many + // items // to return per page. This removes the need to backfill results if Firebase Storage filters // objects that are considered invalid (such as items with two consecutive slashes). if let pageSize = self.pageSize { diff --git a/FirebaseStorage/Sources/Storage.swift b/FirebaseStorage/Sources/Storage.swift index 8c453eeb403..c4e5e85acb6 100644 --- a/FirebaseStorage/Sources/Storage.swift +++ b/FirebaseStorage/Sources/Storage.swift @@ -314,13 +314,13 @@ import FirebaseAuthInterop (suggestedWillRetry: Bool, error: Error?, response: @escaping GTMSessionFetcherRetryResponse) in - var shouldRetry = suggestedWillRetry - // GTMSessionFetcher does not consider being offline a retryable error, but we do, so we - // special-case it here. - if !shouldRetry, error != nil { - shouldRetry = (error as? NSError)?.code == URLError.notConnectedToInternet.rawValue - } - response(shouldRetry) + var shouldRetry = suggestedWillRetry + // GTMSessionFetcher does not consider being offline a retryable error, but we do, so we + // special-case it here. + if !shouldRetry, error != nil { + shouldRetry = (error as? NSError)?.code == URLError.notConnectedToInternet.rawValue + } + response(shouldRetry) } private static func initFetcherServiceForApp(_ app: FirebaseApp, diff --git a/FirebaseStorage/Tests/Integration/StorageIntegration.swift b/FirebaseStorage/Tests/Integration/StorageIntegration.swift index 16543b23170..cd3ce0c270c 100644 --- a/FirebaseStorage/Tests/Integration/StorageIntegration.swift +++ b/FirebaseStorage/Tests/Integration/StorageIntegration.swift @@ -276,7 +276,7 @@ class StorageResultTests: StorageIntegrationCommon { let bundle = Bundle(for: StorageIntegrationCommon.self) let filePath = try XCTUnwrap(bundle.path(forResource: "1mb", ofType: "dat"), "Failed to get filePath") - let data = try XCTUnwrap(try Data(contentsOf: URL(fileURLWithPath: filePath)), + let data = try XCTUnwrap(Data(contentsOf: URL(fileURLWithPath: filePath)), "Failed to load file") let tmpDirURL = URL(fileURLWithPath: NSTemporaryDirectory()) let fileURL = tmpDirURL.appendingPathComponent("LargePutFile.txt") @@ -325,7 +325,7 @@ class StorageResultTests: StorageIntegrationCommon { let bundle = Bundle(for: StorageIntegrationCommon.self) let filePath = try XCTUnwrap(bundle.path(forResource: "1mb", ofType: "dat"), "Failed to get filePath") - let data = try XCTUnwrap(try Data(contentsOf: URL(fileURLWithPath: filePath)), + let data = try XCTUnwrap(Data(contentsOf: URL(fileURLWithPath: filePath)), "Failed to load file") let tmpDirURL = URL(fileURLWithPath: NSTemporaryDirectory()) let fileURL = tmpDirURL.appendingPathComponent("LargePutFile.txt") diff --git a/FirebaseStorage/Tests/Integration/StorageIntegrationCommon.swift b/FirebaseStorage/Tests/Integration/StorageIntegrationCommon.swift index 4b93c2f31a9..47c4fb6f37c 100644 --- a/FirebaseStorage/Tests/Integration/StorageIntegrationCommon.swift +++ b/FirebaseStorage/Tests/Integration/StorageIntegrationCommon.swift @@ -55,7 +55,7 @@ class StorageIntegrationCommon: XCTestCase { let bundle = Bundle(for: StorageIntegrationCommon.self) let filePath = try XCTUnwrap(bundle.path(forResource: "1mb", ofType: "dat"), "Failed to get filePath") - let data = try XCTUnwrap(try Data(contentsOf: URL(fileURLWithPath: filePath)), + let data = try XCTUnwrap(Data(contentsOf: URL(fileURLWithPath: filePath)), "Failed to load file") for largeFile in largeFiles { diff --git a/Firestore/Swift/Source/AsyncAwait/Firestore+AsyncAwait.swift b/Firestore/Swift/Source/AsyncAwait/Firestore+AsyncAwait.swift index faaf3d04b58..2a09c08efab 100644 --- a/Firestore/Swift/Source/AsyncAwait/Firestore+AsyncAwait.swift +++ b/Firestore/Swift/Source/AsyncAwait/Firestore+AsyncAwait.swift @@ -23,7 +23,8 @@ import Foundation /// Loads a Firestore bundle into the local cache. /// - Parameter bundleData: Data from the bundle to be loaded. /// - Throws: `Error` if the bundle data cannot be parsed. - /// - Returns: The final `LoadBundleTaskProgress` that contains the total number of documents loaded. + /// - Returns: The final `LoadBundleTaskProgress` that contains the total number of documents + /// loaded. func loadBundle(_ bundleData: Data) async throws -> LoadBundleTaskProgress { return try await withCheckedThrowingContinuation { continuation in self.loadBundle(bundleData) { progress, error in @@ -40,7 +41,8 @@ import Foundation /// Loads a Firestore bundle into the local cache. /// - Parameter bundleStream: An input stream from which the bundle can be read. /// - Throws: `Error` if the bundle stream cannot be parsed. - /// - Returns: The final `LoadBundleTaskProgress` that contains the total number of documents loaded. + /// - Returns: The final `LoadBundleTaskProgress` that contains the total number of documents + /// loaded. func loadBundle(_ bundleStream: InputStream) async throws -> LoadBundleTaskProgress { return try await withCheckedThrowingContinuation { continuation in self.loadBundle(bundleStream) { progress, error in @@ -54,35 +56,47 @@ import Foundation } } - /// Executes the given updateBlock and then attempts to commit the changes applied within an atomic + /// Executes the given updateBlock and then attempts to commit the changes applied within an + /// atomic /// transaction. /// - /// The maximum number of writes allowed in a single transaction is 500, but note that each usage of + /// The maximum number of writes allowed in a single transaction is 500, but note that each + /// usage of /// `FieldValue.serverTimestamp()`, `FieldValue.arrayUnion()`, `FieldValue.arrayRemove()`, or /// `FieldValue.increment()` inside a transaction counts as an additional write. /// /// In the `updateBlock`, a set of reads and writes can be performed atomically using the - /// `Transaction` object passed to the block. After the `updateBlock` is run, Firestore will attempt - /// to apply the changes to the server. If any of the data read has been modified outside of this - /// transaction since being read, then the transaction will be retried by executing the `updateBlock` + /// `Transaction` object passed to the block. After the `updateBlock` is run, Firestore will + /// attempt + /// to apply the changes to the server. If any of the data read has been modified outside of + /// this + /// transaction since being read, then the transaction will be retried by executing the + /// `updateBlock` /// again. If the transaction still fails after 5 retries, then the transaction will fail. /// - /// Since the `updateBlock` may be executed multiple times, it should avoiding doing anything that + /// Since the `updateBlock` may be executed multiple times, it should avoiding doing anything + /// that /// would cause side effects. /// - /// Any value maybe be returned from the `updateBlock`. If the transaction is successfully committed, - /// then the completion block will be passed that value. The `updateBlock` also has an `NSError` out - /// parameter. If this is set, then the transaction will not attempt to commit, and the given error + /// Any value maybe be returned from the `updateBlock`. If the transaction is successfully + /// committed, + /// then the completion block will be passed that value. The `updateBlock` also has an `NSError` + /// out + /// parameter. If this is set, then the transaction will not attempt to commit, and the given + /// error /// will be returned. /// - /// The `Transaction` object passed to the `updateBlock` contains methods for accessing documents + /// The `Transaction` object passed to the `updateBlock` contains methods for accessing + /// documents /// and collections. Unlike other firestore access, data accessed with the transaction will not /// reflect local changes that have not been committed. For this reason, it is required that all - /// reads are performed before any writes. Transactions must be performed while online. Otherwise, + /// reads are performed before any writes. Transactions must be performed while online. + /// Otherwise, /// reads will fail, the final commit will fail, and this function will return an error. /// /// - Parameter updateBlock The block to execute within the transaction context. - /// - Throws Throws an error if the transaction could not be committed, or if an error was explicitly specified in the `updateBlock` parameter. + /// - Throws Throws an error if the transaction could not be committed, or if an error was + /// explicitly specified in the `updateBlock` parameter. /// - Returns Returns the value returned in the `updateBlock` parameter if no errors occurred. func runTransaction(_ updateBlock: @escaping (Transaction, NSErrorPointer) -> Any?) async throws -> Any? { diff --git a/Firestore/Swift/Source/Codable/ServerTimestamp.swift b/Firestore/Swift/Source/Codable/ServerTimestamp.swift index 46d16a53660..bd211a9c442 100644 --- a/Firestore/Swift/Source/Codable/ServerTimestamp.swift +++ b/Firestore/Swift/Source/Codable/ServerTimestamp.swift @@ -88,7 +88,7 @@ public struct ServerTimestamp: Codable if container.decodeNil() { value = nil } else { - value = try Value.wrap(try container.decode(Timestamp.self)) + value = try Value.wrap(container.decode(Timestamp.self)) } } diff --git a/Firestore/Swift/Source/PropertyWrapper/FirestoreQuery.swift b/Firestore/Swift/Source/PropertyWrapper/FirestoreQuery.swift index 5cfd77f4742..16ca88baa27 100644 --- a/Firestore/Swift/Source/PropertyWrapper/FirestoreQuery.swift +++ b/Firestore/Swift/Source/PropertyWrapper/FirestoreQuery.swift @@ -130,7 +130,8 @@ public struct FirestoreQuery: DynamicProperty { /// If any errors occurred, they will be exposed here as well. public var error: Error? - /// The type of animation to apply when updating the view. If this is ommitted then no animations are fired. + /// The type of animation to apply when updating the view. If this is ommitted then no + /// animations are fired. public var animation: Animation? } diff --git a/Firestore/Swift/Tests/Integration/AggregationIntegrationTests.swift b/Firestore/Swift/Tests/Integration/AggregationIntegrationTests.swift index b1b01393370..2155a966df4 100644 --- a/Firestore/Swift/Tests/Integration/AggregationIntegrationTests.swift +++ b/Firestore/Swift/Tests/Integration/AggregationIntegrationTests.swift @@ -18,7 +18,8 @@ import FirebaseFirestore import FirebaseFirestoreSwift import Foundation -// TODO(sum/avg) remove `sumAvgIsPublic` from the directive below to enable these tests when sum/avg is public +// TODO(sum/avg) remove `sumAvgIsPublic` from the directive below to enable these tests when sum/avg +// is public #if sumAvgIsPublic && swift(>=5.5.2) @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *) @@ -386,7 +387,8 @@ import Foundation .aggregate([AggregateField.count(), AggregateField.sum("notInMyDocs"), AggregateField.average("notInMyDocs")]).getAggregation(source: .server) - // Count - 0 because aggregation is performed on documents matching the query AND documents that have all aggregated fields + // Count - 0 because aggregation is performed on documents matching the query AND documents + // that have all aggregated fields XCTAssertEqual(snapshot.get(AggregateField.count()) as? NSNumber, 0) // Sum diff --git a/Mintfile b/Mintfile index 4e60f1d062d..5fc562819ee 100644 --- a/Mintfile +++ b/Mintfile @@ -1 +1 @@ -nicklockwood/SwiftFormat@0.49.2 +nicklockwood/SwiftFormat@0.51.12 diff --git a/ReleaseTooling/Sources/FirebaseManifest/Pod.swift b/ReleaseTooling/Sources/FirebaseManifest/Pod.swift index 83d45e7d26b..47d2d26ee6c 100755 --- a/ReleaseTooling/Sources/FirebaseManifest/Pod.swift +++ b/ReleaseTooling/Sources/FirebaseManifest/Pod.swift @@ -28,7 +28,8 @@ public struct Pod { public let allowWarnings: Bool /// Set of platforms (e.g. "ios", "macos", or "tvos") to build this pod for. public let platforms: Set - /// Whether or not the pod is planned for publicly releasing (as some pods are for internal/testing use). + /// Whether or not the pod is planned for publicly releasing (as some pods are for + /// internal/testing use). public let releasing: Bool /// Whether or not the pod is the top level pod in the zip distribution. public let zip: Bool diff --git a/ReleaseTooling/Sources/FirebaseReleaser/InitializeRelease.swift b/ReleaseTooling/Sources/FirebaseReleaser/InitializeRelease.swift index cfe94bf0b40..d37a7afe8b3 100644 --- a/ReleaseTooling/Sources/FirebaseReleaser/InitializeRelease.swift +++ b/ReleaseTooling/Sources/FirebaseReleaser/InitializeRelease.swift @@ -101,7 +101,8 @@ struct InitializeRelease { } } - /// Update the existing version to the given version by writing to a given string using the provided range. + /// Update the existing version to the given version by writing to a given string using the + /// provided range. /// - Parameters: /// - contents: A reference to a String containing a version that will be updated. /// - range: The range containing a version substring that will be updated. diff --git a/ReleaseTooling/Sources/Utils/FileManager+Utils.swift b/ReleaseTooling/Sources/Utils/FileManager+Utils.swift index 2af70aa4126..0896f01be72 100644 --- a/ReleaseTooling/Sources/Utils/FileManager+Utils.swift +++ b/ReleaseTooling/Sources/Utils/FileManager+Utils.swift @@ -84,7 +84,8 @@ public extension FileManager { return cacheRoot } - /// Removes a directory or file if it exists. This is helpful to clean up error handling for checks that + /// Removes a directory or file if it exists. This is helpful to clean up error handling for + /// checks that /// shouldn't fail. The only situation this could potentially fail is permission errors or if a /// folder is open in Finder, and in either state the user needs to close the window or fix the /// permissions. A fatal error will be thrown in those situations. @@ -101,7 +102,8 @@ public extension FileManager { } } - /// Enable a single unique temporary workspace per execution with a sortable and readable timestamp. + /// Enable a single unique temporary workspace per execution with a sortable and readable + /// timestamp. private static func timeStamp() -> String { let formatter = DateFormatter() formatter.dateFormat = "YYYY-MM-dd'T'HH-mm-ss" diff --git a/ReleaseTooling/Sources/Utils/String+Utils.swift b/ReleaseTooling/Sources/Utils/String+Utils.swift index a37a97152e8..5b4efc8e638 100644 --- a/ReleaseTooling/Sources/Utils/String+Utils.swift +++ b/ReleaseTooling/Sources/Utils/String+Utils.swift @@ -18,9 +18,11 @@ import Foundation /// Utilities to simplify String operations. public extension String { - /// Finds and returns the ranges of all occurrences of a given string within a given range of the String, subject to given options, + /// Finds and returns the ranges of all occurrences of a given string within a given range of the + /// String, subject to given options, /// using the specified locale, if any. - /// - Returns: An an optional array of ranges where each range corresponds to an occurence of the substring in the given string. + /// - Returns: An an optional array of ranges where each range corresponds to an occurence of the + /// substring in the given string. func ranges(of substring: T, options: CompareOptions = .literal, locale: Locale? = nil) -> [Range] { var ranges: [Range] = [] diff --git a/ReleaseTooling/Sources/ZipBuilder/CarthageUtils.swift b/ReleaseTooling/Sources/ZipBuilder/CarthageUtils.swift index 6f251ca3190..dfd4407fe16 100644 --- a/ReleaseTooling/Sources/ZipBuilder/CarthageUtils.swift +++ b/ReleaseTooling/Sources/ZipBuilder/CarthageUtils.swift @@ -304,7 +304,8 @@ extension CarthageUtils { } /// Get the JSON filename for a product - /// Consider using just the product name post Firebase 7. The conditions are to handle Firebase 6 compatibility. + /// Consider using just the product name post Firebase 7. The conditions are to handle Firebase 6 + /// compatibility. /// /// - Parameters: /// - product: The name of the Firebase product. diff --git a/ReleaseTooling/Sources/ZipBuilder/CocoaPodUtils.swift b/ReleaseTooling/Sources/ZipBuilder/CocoaPodUtils.swift index 5a8fde9e9cd..c61bce4ef7f 100644 --- a/ReleaseTooling/Sources/ZipBuilder/CocoaPodUtils.swift +++ b/ReleaseTooling/Sources/ZipBuilder/CocoaPodUtils.swift @@ -163,7 +163,8 @@ enum CocoaPodUtils { localPodspecPath: localPodspecPath) } - /// Install an array of pods in a specific directory, returning a dictionary of PodInfo for each pod + /// Install an array of pods in a specific directory, returning a dictionary of PodInfo for each + /// pod /// that was installed. /// - Parameters: /// - pods: List of VersionedPods to install @@ -413,10 +414,12 @@ enum CocoaPodUtils { /// - Returns: A tuple of the framework and version, if it can be parsed. private static func detectVersion(fromLine input: String) -> (framework: String, version: String)? { - // Get the components of the line to parse them individually. Ignore any whitespace only Strings. + // Get the components of the line to parse them individually. Ignore any whitespace only + // Strings. let components = input.components(separatedBy: " ").filter { !$0.isEmpty } - // Expect three components: the `-`, the pod name, and the version in parens. This will filter out + // Expect three components: the `-`, the pod name, and the version in parens. This will filter + // out // dependencies that have version requirements like `(~> 3.2.1)` in it. guard components.count == 3 else { return nil } diff --git a/ReleaseTooling/Sources/ZipBuilder/FirebaseBuilder.swift b/ReleaseTooling/Sources/ZipBuilder/FirebaseBuilder.swift index fd1ed5bf90d..8ddd97b44df 100644 --- a/ReleaseTooling/Sources/ZipBuilder/FirebaseBuilder.swift +++ b/ReleaseTooling/Sources/ZipBuilder/FirebaseBuilder.swift @@ -16,7 +16,8 @@ import Foundation -/// Wrapper for the Firebase zip build. Unlike the generic zip builder, the Firebase build creates a two-level +/// Wrapper for the Firebase zip build. Unlike the generic zip builder, the Firebase build creates +/// a two-level /// zip with the option to install different Firebase library subsets. struct FirebaseBuilder { /// ZipBuilder instance. @@ -50,7 +51,8 @@ struct FirebaseBuilder { let candidateName = "Firebase-\(firebaseVersion)-latest.zip" let zipped = Zip.zipContents(ofDir: location, name: candidateName) - // If an output directory was specified, copy the Zip file to that directory. Otherwise just print + // If an output directory was specified, copy the Zip file to that directory. Otherwise just + // print // the location for further use. if let outputDir = zipBuilder.paths.outputDir { do { diff --git a/ReleaseTooling/Sources/ZipBuilder/ModuleMapBuilder.swift b/ReleaseTooling/Sources/ZipBuilder/ModuleMapBuilder.swift index dad59428147..63610e0420b 100755 --- a/ReleaseTooling/Sources/ZipBuilder/ModuleMapBuilder.swift +++ b/ReleaseTooling/Sources/ZipBuilder/ModuleMapBuilder.swift @@ -121,8 +121,10 @@ struct ModuleMapBuilder { // MARK: - Internal Functions - /// Build a module map for a single framework. A CocoaPod install is run to extract the required frameworks - /// and libraries from the generated xcconfig. All previously installed dependent pods are put into the Podfile + /// Build a module map for a single framework. A CocoaPod install is run to extract the required + /// frameworks + /// and libraries from the generated xcconfig. All previously installed dependent pods are put + /// into the Podfile /// to make sure we install the right version and from the right location. private func generate(framework: FrameworkInfo) { let podName = framework.versionedPod.name @@ -142,7 +144,8 @@ struct ModuleMapBuilder { .moduleMapContents = makeModuleMap(forFramework: framework, withXcconfigFile: xcconfigFile) } - /// Convert a list of versioned pods to a list of versioned pods specified with all needed subspecs. + /// Convert a list of versioned pods to a list of versioned pods specified with all needed + /// subspecs. private func allSubspecList(framework: FrameworkInfo) -> [CocoaPodUtils.VersionedPod] { let name = framework.versionedPod.name let version = framework.versionedPod.version diff --git a/ReleaseTooling/Sources/ZipBuilder/ZipBuilder.swift b/ReleaseTooling/Sources/ZipBuilder/ZipBuilder.swift index 80c5c688670..29b1b7ddbc8 100644 --- a/ReleaseTooling/Sources/ZipBuilder/ZipBuilder.swift +++ b/ReleaseTooling/Sources/ZipBuilder/ZipBuilder.swift @@ -59,7 +59,8 @@ struct ZipBuilder { /// The directory that contains the properly assembled release artifacts. let zipDir: URL - /// The directory that contains the properly assembled release artifacts for Carthage if building it. + /// The directory that contains the properly assembled release artifacts for Carthage if + /// building it. let carthageDir: URL? } @@ -375,7 +376,8 @@ struct ZipBuilder { /// 4. Assemble the `README` file based off the template and copy it to the directory. /// 5. Return the URL of the folder containing the contents of the Zip file. /// - /// - Returns: Return the URL of the folder containing the contents of the Zip or Carthage distribution. + /// - Returns: Return the URL of the folder containing the contents of the Zip or Carthage + /// distribution. /// - Throws: One of many errors that could have happened during the build phase. private func assembleDistributions(withPackageKind packageKind: String, podsToInstall: [CocoaPodUtils.VersionedPod], @@ -613,7 +615,8 @@ struct ZipBuilder { return copiedFrameworkNames } - /// Copies required files from the Firebase pod (`Firebase.h`, `module.modulemap`, and `NOTICES`) into + /// Copies required files from the Firebase pod (`Firebase.h`, `module.modulemap`, and `NOTICES`) + /// into /// the given `zipDir`. Will cause a fatalError if anything fails since the zip file can't exist /// without these files. private func copyFirebasePodFiles(fromDir firebasePodDir: URL, to zipDir: URL) { @@ -730,7 +733,8 @@ struct ZipBuilder { frameworksToIgnore: frameworksToIgnore) let copiedFrameworks = namedFrameworks.filter { - // Skip frameworks that aren't contained in the "frameworksToIgnore" array and the Firebase pod. + // Skip frameworks that aren't contained in the "frameworksToIgnore" array and the Firebase + // pod. !(frameworksToIgnore.contains($0) || $0 == "Firebase") } diff --git a/scripts/create_spec_repo/Sources/SpecRepoBuilder/main.swift b/scripts/create_spec_repo/Sources/SpecRepoBuilder/main.swift index 3c512598212..f970c7bc6c4 100644 --- a/scripts/create_spec_repo/Sources/SpecRepoBuilder/main.swift +++ b/scripts/create_spec_repo/Sources/SpecRepoBuilder/main.swift @@ -328,7 +328,7 @@ struct SpecRepoBuilder: ParsableCommand { ) print("Found following unhidden dirs: \(dirs)") for dir in dirs { - guard let isDir = (try dir.resourceValues(forKeys: [.isDirectoryKey])).isDirectory else { + guard let isDir = try (dir.resourceValues(forKeys: [.isDirectoryKey])).isDirectory else { print("Error: cannot determine if \(dir.path) is a directory or not.") Self .exit(withError: SpecRepoBuilderError diff --git a/scripts/health_metrics/generate_code_coverage_report/Package.swift b/scripts/health_metrics/generate_code_coverage_report/Package.swift index 1fd5b52096c..caffe36fdac 100644 --- a/scripts/health_metrics/generate_code_coverage_report/Package.swift +++ b/scripts/health_metrics/generate_code_coverage_report/Package.swift @@ -21,7 +21,8 @@ import PackageDescription let package = Package( name: "CodeCoverage", products: [ - // Products define the executables and libraries a package produces, and make them visible to other packages. + // Products define the executables and libraries a package produces, and make them visible to + // other packages. .executable( name: "CoverageReportGenerator", targets: ["CoverageReportGenerator"] diff --git a/scripts/health_metrics/generate_code_coverage_report/Sources/IncrementalCoverageReportGenerator/main.swift b/scripts/health_metrics/generate_code_coverage_report/Sources/IncrementalCoverageReportGenerator/main.swift index 54db6e24299..89398c89595 100644 --- a/scripts/health_metrics/generate_code_coverage_report/Sources/IncrementalCoverageReportGenerator/main.swift +++ b/scripts/health_metrics/generate_code_coverage_report/Sources/IncrementalCoverageReportGenerator/main.swift @@ -84,7 +84,8 @@ struct IncrementalCoverageReportGenerator: ParsableCommand { /// The output will have the file name, line execution counts and the xcresult bundle name. func createLineCoverageRecord(from coverageFile: URL, changedFile: String, lineCoverage: [LineCoverage]? = nil) -> [LineCoverage] { - // The indices of the array represent the (line index - 1), while the value is the execution counts. + // The indices of the array represent the (line index - 1), while the value is the execution + // counts. // Unexecutable lines, e.g. comments, will be nil here. var lineExecutionCounts: [Int?] = [] do { @@ -117,17 +118,21 @@ struct IncrementalCoverageReportGenerator: ParsableCommand { } } - /// This function is to get union of newly added file lines and lines execution counts, from a xcresult bundle. - /// Return an array of LineCoverage, which includes uncovered line indices of a file and its xcresult bundle source. + /// This function is to get union of newly added file lines and lines execution counts, from a + /// xcresult bundle. + /// Return an array of LineCoverage, which includes uncovered line indices of a file and its + /// xcresult bundle source. func getUncoveredFileLines(fromDiff changedFiles: [FileIncrementalChanges], xcresultFile: URL, archiveRootPath rootPath: String) -> [LineCoverage] { var uncoveredFiles: [LineCoverage] = [] for change in changedFiles { let archiveFilePath = URL(string: rootPath)!.appendingPathComponent(change.file) - // tempOutputFile is a temp file, with the xcresult bundle name, including line execution counts of a file + // tempOutputFile is a temp file, with the xcresult bundle name, including line execution + // counts of a file let tempOutputFile = xcresultFile.deletingPathExtension() - // Fetch line execution report of a file from a xcresult bundle into a temp file, which has the same name as the xcresult bundle. + // Fetch line execution report of a file from a xcresult bundle into a temp file, which has + // the same name as the xcresult bundle. Shell.run( "\(Constants.xcovCommand) \(archiveFilePath.absoluteString) \(xcresultFile.path) > \(tempOutputFile.path)", displayCommand: true, @@ -164,7 +169,8 @@ struct IncrementalCoverageReportGenerator: ParsableCommand { func run() throws { let enumerator = FileManager.default.enumerator(atPath: xcresultDir.path) var uncoveredFiles: [LineCoverage] = [] - // Search xcresult bundles from xcresultDir and get union of `git diff` report and xccov output to generate a list of lineCoverage including files and their uncovered lines. + // Search xcresult bundles from xcresultDir and get union of `git diff` report and xccov output + // to generate a list of lineCoverage including files and their uncovered lines. while let file = enumerator?.nextObject() as? String { var isDir: ObjCBool = false let xcresultURL = xcresultDir.appendingPathComponent(file, isDirectory: true)