Search code examples
swiftsamplecombineaws-amplify

AWS Amplify for Swift / SwiftUI under Combine framework cause headache


Does anybody have a working copy/sample of using AWS Amplify with the Combine framework?

The samples provided https://docs.amplify.aws/lib/datastore/data-access/q/platform/ios https://docs.amplify.aws/lib/auth/getting-started/q/platform/ios#configure-auth-category Seems really straight forward and I'm using it verbatim, but since I'm not well versed in Combine, it could be that I'm losing the sink, especially when these functions are placed in an Observable class.

And when going with URL session, my attempts deliver a load of the same error:

Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service on pid 0 named com.apple.commcenter.coretelephony.xpc was invalidated from this process." UserInfo={NSDebugDescription=The connection to service on pid 0 named com.apple.commcenter.coretelephony.xpc was invalidated from this process.}


Solution

  • Here's an example showing how to sign in with username and password:

    import SwiftUI
    import Combine
    import Amplify
    
    enum AuthState {
      case signUp
      case login
      case confirmCode(email: String)
      case session(user: AuthUser)
    }
    
    final class SessionManager: ObservableObject {
      @Published var authState: AuthState = .login
      var storage = Set<AnyCancellable>()
    
      func getCurrentAuthUser() {
        if let user = Amplify.Auth.getCurrentUser() {
          DispatchQueue.main.async {
            self.authState = .session(user: user)
          }
        } else {
          DispatchQueue.main.async {
            self.authState = .login
          }
        }
      }
    
      func signIn(email: String, password: String) {
        Amplify.Auth.signIn(username: email, password: password)
          .resultPublisher
          .receive(on: DispatchQueue.main)
          .sink(
            receiveCompletion: {
              if case .failure(let error) = $0 {
                print("Sign in error: \(error)")
              }
            }) { result in
            self.getCurrentAuthUser()
          }.store(in: &self.storage)
      }
    }