새소식

개발일지

UniNuri (2) : Amplify 연결 및 Data 전송

  • -

 

공식 문서 보고 진행을 하였다.

https://docs.amplify.aws/lib/datastore/getting-started/q/platform/ios/

 

https://docs.amplify.aws/lib/datastore/getting-started/q/platform/ios/

 

docs.amplify.aws

 

 

- AppDelegate 추가

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        do {
              // AmplifyModels is generated in the previous step
              
              // 전송 api Plugin
              let apiPlugin = AWSAPIPlugin(modelRegistration: AmplifyModels())
              // 데이터 만드는 api Plugin
              let dataStorePlugin = AWSDataStorePlugin(modelRegistration: AmplifyModels())
              try Amplify.add(plugin: apiPlugin)
              try Amplify.add(plugin: dataStorePlugin)
              try Amplify.configure()
              print("Amplify configured with DataStore plugin")
          } catch {
              print("Failed to initialize Amplify with \(error)")
              return false
          }
        return true
    }

 

내가 테스트 해볼 테이블의 형식이다.

 

 

 

이제 데이터를 생성하고 읽고 지우기 만들어볼려고 공식 문서 참고하는데  Task, await, async이 등장한다.

 

비동기 함수 관련 내용은 아래 내용으로 정리하였다.

 

https://kimkhuna99.tistory.com/104

 

[Swift] Task, await, async

Introduction Task, await, async은 Swift5.5에서 비동기 프로그래밍을 위해 도입되었다. 세 가지를 알아보기 전에 간단하게 비동기에 관하여 정리하고 들어가려고 한다. - 비동기(Asynchronus : 동시에 일어나

kimkhuna99.tistory.com

 

아무튼 공식 문서를 참고하여 만든 소스...

 

func writeData() async{
    let post = Univ(id: UUID().uuidString, groupName: "test", groupInfo: "test", createdAt: .now(), updatedAt: .now())
    do {
        try await Amplify.DataStore.save(post)
        print("Post saved successfully!")
    } catch let error as DataStoreError {
        print("Error saving post \(error)")
    } catch {
        print("Unexpected error \(error)")
    }
 }
    
func readData() async{
    do {
        let posts = try await Amplify.DataStore.query(Univ.self)
        print("Posts retrieved successfully: \(posts)")
    } catch let error as DataStoreError {
        print("Error retrieving posts \(error)")
    } catch {
        print("Unexpected error \(error)")
    }
}

func deletData() async{
    do {
        try await Amplify.DataStore.delete(Univ.self, withId: "ID값")
        print("Post deleted!")
    } catch let error as DataStoreError {
        print("Error deleting post - \(error)")
    } catch {
        print("Unexpected error \(error)")
    }
}

 

버튼에 액션을 추가해서 함수 선언

    @IBAction func btnSendDataClicked(_ sender: UIButton) {
        Task{
            await self.writeData()
        }
    }

 

 

결과적으로 잘 동작하였다.

 

오늘은 처음 Amplify를 다뤄보아서 연동해보면서 테스트하고 더 배우는 계기가 되었다.

 

 

728x90
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.