반응형
1. Create 구현하기
private func addNotice(_ title: String, _ text: String, _ local: String, _ Member: String, _ ImageName: String, _ ImageUrl: String, _ priority: Priority, _ User: String) async {
do{
//date
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd HH:mm"
let dateString = dateFormatter.string(from: currentDate)
let item = Notice(id: UUID().uuidString, noticeTitle: title, noticeText: text, Local: local, Member: Member, ImageName: ImageName, ImageUrl: ImageUrl, priority: priority, User: User, Date: dateString)
_ = try await Amplify.DataStore.save(item)
print(dateString)
} catch {
let error = UIAlertController(title: "ERROR", message: "Could not save item to dataStore: \(error)", preferredStyle: UIAlertController.Style.alert)
let yError = UIAlertAction(title: "확인", style: UIAlertAction.Style.default, handler: nil)
error.addAction(yError)
present(error, animated: true, completion: nil)
}
}
2. Read 구현하기
기본적인 형식의 경우
private func readNotice() async {
do{
let notices = try await Amplify.DataStore.query(Notice.self)
for notice in notices {
addArticle = ["noticeId":notice.id,"local":notice.Local,"member":notice.Member,"titleImgName":notice.ImageName,"titleImgUrl":notice.ImageUrl,"title":notice.noticeTitle,"User":notice.User,"Date":notice.Date]
articleList.append(addArticle)
let users = try await Amplify.DataStore.query(User.self, where: User.keys.id.eq(notice.User))
for user in users{
addArticleUser = ["userNickName":user.UserNickName,"userImgName":user.UserImageName,"userImgUrl":user.UserImageUrl,"sex":user.UserSex,"age":user.UserAge]
articleList.append(addArticleUser)
}
}
articleList.reverse()
} catch {
print("Could not query DataStore: \(error)")
}
}
해당 코드를 사용하였습니다.
허나, 응용 버전으로 각각의 조건마다 읽어오는 data를 다르게 하는 방식도 소개해보겠습니다.
저의 경우 지역, 성별, 인원, 나이로 구분하여 읽어와야 했습니다.
따라서 조건바다 읽어오는 쿼리문을 바꿔주었습니다.
아래는 커스텀 코드입니다.
private func originReadNotice() async {
var notices: [Notice] = []
articleList = []
do{
if(testLocal != nil && testLocal != "전체지역"){
if(testMember != nil && testMember != "전체인원"){
notices = try await Amplify.DataStore.query(Notice.self, where: Notice.keys.Local.eq(testLocal) && Notice.keys.Member.eq(testMember))
} else {
notices = try await Amplify.DataStore.query(Notice.self, where: Notice.keys.Local.eq(testLocal))
}
} else { //전체 지역 고려
if(testMember != nil && testMember != "전체인원"){
notices = try await Amplify.DataStore.query(Notice.self, where: Notice.keys.Member.eq(testMember))
} else{ //전체 인원 고려(o)
notices = try await Amplify.DataStore.query(Notice.self)
}
}
for notice in notices {
addArticle = ["noticeId":notice.id,"local":notice.Local,"member":notice.Member,"titleImgName":notice.ImageName,"titleImgUrl":notice.ImageUrl,"title":notice.noticeTitle,"text":notice.noticeText ,"User":notice.User,"Date":notice.Date]
articleList.append(addArticle)
if(testSex != nil && testSex != "전체성별"){
if(testAge != nil && testAge != 0){
switch testAge {
case 0:
let users = try await Amplify.DataStore.query(User.self, where: User.keys.id.eq(notice.User) && User.keys.UserSex.eq(testSex))
for user in users{
addArticleUser = ["userNickName":user.UserNickName,"userImgName":user.UserImageName,"userImgUrl":user.UserImageUrl,"sex":user.UserSex,"age":user.UserAge]
articleList.append(addArticleUser)
}
case 2:
let users = try await Amplify.DataStore.query(User.self, where: User.keys.id.eq(notice.User) && User.keys.UserSex.eq(testSex) && User.keys.UserAge >= 20 && User.keys.UserAge < 30)
for user in users{
addArticleUser = ["userNickName":user.UserNickName,"userImgName":user.UserImageName,"userImgUrl":user.UserImageUrl,"sex":user.UserSex,"age":user.UserAge]
articleList.append(addArticleUser)
}
case 3:
let users = try await Amplify.DataStore.query(User.self, where: User.keys.id.eq(notice.User) && User.keys.UserSex.eq(testSex) && User.keys.UserAge >= 30 && User.keys.UserAge < 40)
for user in users{
addArticleUser = ["userNickName":user.UserNickName,"userImgName":user.UserImageName,"userImgUrl":user.UserImageUrl,"sex":user.UserSex,"age":user.UserAge]
articleList.append(addArticleUser)
}
default:
return
}
} else {
let users = try await Amplify.DataStore.query(User.self, where: User.keys.id.eq(notice.User) && User.keys.UserSex.eq(testSex))
for user in users{
addArticleUser = ["userNickName":user.UserNickName,"userImgName":user.UserImageName,"userImgUrl":user.UserImageUrl,"sex":user.UserSex,"age":user.UserAge]
articleList.append(addArticleUser)
}
}
} else {
if(testAge != nil && testAge != 0){
switch testAge {
case 0:
let users = try await Amplify.DataStore.query(User.self, where: User.keys.id.eq(notice.User))
for user in users{
addArticleUser = ["userNickName":user.UserNickName,"userImgName":user.UserImageName,"userImgUrl":user.UserImageUrl,"sex":user.UserSex,"age":user.UserAge]
articleList.append(addArticleUser)
}
case 2:
let users = try await Amplify.DataStore.query(User.self, where: User.keys.id.eq(notice.User) && User.keys.UserAge >= 20 && User.keys.UserAge < 30)
for user in users{
addArticleUser = ["userNickName":user.UserNickName,"userImgName":user.UserImageName,"userImgUrl":user.UserImageUrl,"sex":user.UserSex,"age":user.UserAge]
articleList.append(addArticleUser)
}
case 3:
let users = try await Amplify.DataStore.query(User.self, where: User.keys.id.eq(notice.User) && User.keys.UserAge >= 30 && User.keys.UserAge < 40)
for user in users{
addArticleUser = ["userNickName":user.UserNickName,"userImgName":user.UserImageName,"userImgUrl":user.UserImageUrl,"sex":user.UserSex,"age":user.UserAge]
articleList.append(addArticleUser)
}
default:
return
}
} else {
let users = try await Amplify.DataStore.query(User.self, where: User.keys.id.eq(notice.User))
for user in users{
addArticleUser = ["userNickName":user.UserNickName,"userImgName":user.UserImageName,"userImgUrl":user.UserImageUrl,"sex":user.UserSex,"age":user.UserAge]
articleList.append(addArticleUser)
}
}
}
}
articleList.reverse()
} catch {
print("Could not query DataStore: \(error)")
}
}
3. Update 구현하기
private func updateNotice(_ noticeId: String) async {
do {
let notices = try await Amplify.DataStore.query(Notice.self,
where: Notice.keys.id.eq(noticeId))
guard notices.count == 1, var updatedNotice = notices.first else {
print("Did not find exactly one todo, bailing")
return
}
updatedNotice.noticeTitle = "File quarterly taxes"
updatedNotice.noticeText = ""
updatedNotice.Local = ""
//image
let fileName = selectedFileName
let fileUrl = selectedFileUrl
updatedNotice.ImageName = fileName!
updatedNotice.ImageUrl = fileUrl?.absoluteString ?? ""
let savedNotice = try await Amplify.DataStore.save(updatedNotice)
} catch {
print("Unable to perform operation: \(error)")
}
}
4. Delete 구현하기
우선 전체 data를 지우는 코드 입니다.
private func deleteAllTodos() async {
do {
let todos = try await Amplify.DataStore.query(Notice.self)
for todo in todos {
try await Amplify.DataStore.delete(todo)
}
} catch {
print("Unable to perform operation: \(error)")
}
}
만약 특정 data만 지우고 싶다면 read때와 마찬가지로 쿼리문을 이용하여 커스텀하여 작성하면 됩니다.
아래의 코드가 커스텀 코드입니다.
private func deleteTodo(_ title: String) async {
do {
let todos = try await Amplify.DataStore.query(Notice.self,
where: Notice.keys.noticeTitle.eq("File quarterly taxes"))
guard todos.count == 1, let toDeleteTodo = todos.first else {
print("Did not find exactly one todo, bailing")
return
}
try await Amplify.DataStore.delete(toDeleteTodo)
} catch {
print("Unable to perform operation: \(error)")
}
}
이렇게 ios[swift]에서 AWS Amplify를 이용하여 CRUD를 구현하는 코드들을 알아봤습니다.
허나, 마지막으로 중요한 점은 해당 코드 과정이 수행된 후에는 subscribe라는 코드를 수행해야 정상적으로 수행이 됩니다.
마지막으로 subscribe 코드에 대해서 알아보겟습니다.
1단계) subscribe 변수 선언
var noticeSubscription: AmplifyAsyncThrowingSequence<MutationEvent>?
2단계) subscribe 함수 구현
func subscribeToNotice() async {
let noticeSubscription = Amplify.DataStore.observe(Notice.self)
self.noticeSubscription = noticeSubscription
do {
for try await changes in noticeSubscription {
print("Subscription received mutation: \(changes)")
}
} catch {
print("Subscription received error: \(error)")
}
}
func unsubscribeFromPosts() {
noticeSubscription?.cancel()
}
이렇게 내용은 마무리 되엇습니다.
이제 다음내용으로는 s3 storage로 부터 image를 저장하고 불러오는 내용에 대하여 작성하겠습니다.
반응형
'ios 앱개발' 카테고리의 다른 글
[SWIFT] IOS에서 카카오 로그인 구현하기 with AWS Amplify (0) | 2024.02.11 |
---|---|
[SWIFT] IOS에서 AWS Amplify를 이용해 이미지 저장과 불러오기(S3 storage) (0) | 2024.02.10 |
ios에서 AWS Amplify S3를 이용하여 image upload, download하기 (0) | 2023.07.21 |
ios에서 AWS Amplify를 사용할 때 GraphQL 수정방법 (0) | 2023.07.15 |
XCODE tableview에 segue 여러개 연결하여 view controller 여러개 사용하기 (0) | 2023.06.10 |