iOS
...
Data Objects
API การจัดการข้อมูลบน Swift ด้วย Parse SDK
13 นาที
解析数据类型在swift上 บทนำ เมื่อบันทึกข้อมูลในฐานข้อมูล back4app แต่ละเอนทิตีจะถูกเก็บในรูปแบบคู่คีย์ ค่า ประเภทข้อมูลสำหรับฟิลด์ค่าเริ่มต้นจะมีตั้งแต่ประเภทพื้นฐาน (เช่น string , int , double , float , และ bool ) ไปจนถึงโครงสร้างที่ซับซ้อนมากขึ้น ข้อกำหนดหลักสำหรับการเก็บข้อมูลในฐานข้อมูล back4app คือเอนทิตีจะต้องปฏิบัติตาม parseswift โปรโตคอล โปรโตคอลนี้จะให้ชุดของวิธีการในการเก็บ อัปเดต และลบอินสแตนซ์ใดๆ ของเอนทิตี ในคู่มือนี้ คุณจะได้เรียนรู้วิธีการสร้างและตั้งค่าเอนทิตีเพื่อบันทึกลงในฐานข้อมูล back4app ของคุณ ในตัวอย่างโปรเจกต์เอนทิตีที่เรากำลังเก็บข้อมูลเกี่ยวกับสูตรอาหาร บทเรียนนี้ใช้แอปพื้นฐานที่สร้างขึ้นใน xcode 12 และ ios 14 ในทุกช่วงเวลา คุณสามารถเข้าถึงโปรเจกต์ทั้งหมดได้ผ่านที่เก็บ github ของเรา ที่เก็บตัวอย่าง ios เป้าหมาย เพื่อให้เข้าใจว่าอ็อบเจ็กต์ถูกวิเคราะห์และจัดเก็บในฐานข้อมูล back4app อย่างไร ข้อกำหนดเบื้องต้น ในการทำให้การเริ่มต้นอย่างรวดเร็วนี้เสร็จสมบูรณ์ คุณต้องการ xcode แอปที่สร้างขึ้นที่ back4app ติดตาม บทแนะนำการสร้างแอป parse ใหม่ เพื่อเรียนรู้วิธีการสร้างแอป parse ที่ back4app หมายเหตุ ติดตาม บทแนะนำการติดตั้ง parse sdk (swift) เพื่อสร้างโปรเจกต์ xcode ที่เชื่อมต่อกับ back4app การทำความเข้าใจแอปสูตรอาหารของเรา ฟังก์ชันการทำงานของแอปขึ้นอยู่กับแบบฟอร์มที่ผู้ใช้สามารถกรอกข้อมูลเกี่ยวกับสูตรอาหารได้ ขึ้นอยู่กับข้อมูล ประเภทข้อมูลอาจแตกต่างกัน ในตัวอย่างของเรา สูตรอาหารมีคุณสมบัติดังต่อไปนี้ สนาม ประเภทข้อมูล คำอธิบาย ชื่อ สตริง ชื่อของสูตรอาหาร จำนวนเสิร์ฟ อินท จำนวนการเสิร์ฟ มีให้บริการ บูล กำหนดว่าเมนูอาหารมีอยู่หรือไม่ หมวดหมู่ หมวดหมู่ การจัดประเภทที่กำหนดเองซึ่งจัดหมวดหมู่สูตรอาหารเป็นสามประเภท อาหารเช้า, อาหารกลางวัน และอาหารเย็น ส่วนผสม \[ส่วนผสม] ชุดของส่วนผสมที่อยู่ในโครงสร้าง customingredient ตัวเลือกด้านข้าง \[สตริง] ชื่อของตัวเลือกเพิ่มเติมที่สูตรอาหารมาพร้อมกับ ข้อมูลโภชนาการ \[สตริง สตริง] พจนานุกรมที่มีข้อมูลเกี่ยวกับเนื้อหาทางโภชนาการของสูตรอาหาร วันที่วางจำหน่าย วันที่ วันที่แสดงเมื่อสูตรอาหารพร้อมใช้งาน นอกจากนี้ยังมีประเภทข้อมูลเพิ่มเติมที่ใช้ในการดำเนินการฟังก์ชันฐานข้อมูล เช่น ความสัมพันธ์ระหว่างวัตถุ ประเภทข้อมูลเหล่านี้ไม่ได้ถูกกล่าวถึงในบทช่วยสอนนี้ การอ้างอิงคำสั่งอย่างรวดเร็วที่เราจะใช้ เมื่อมีวัตถุ เช่น สูตรอาหาร หากคุณต้องการบันทึกมันในฐานข้อมูล back4app คุณต้องทำให้วัตถุนี้สอดคล้องกับโปรโตคอล parseswift (ซึ่งมีให้ผ่าน sdk ของ parseswift) ก่อน 1 import foundation 2 import parseswift 3 4 struct recipe parseobject { 5 /// enumeration for the recipe category 6 enum category int, caseiterable, codable { 7 case breakfast = 0, lunch = 1, dinner = 2 8 9 var title string { 10 switch self { 11 case breakfast return "breakfast" 12 case lunch return "lunch" 13 case dinner return "dinner" 14 } 15 } 16 } 17 18 19 20 /// a string type property 21 var name string? 22 23 /// an integer type property 24 var servings int? 25 26 /// a double (or float ) type property 27 var price double? 28 29 /// a boolean type property 30 var isavailable bool? 31 32 /// an enumeration type property 33 var category category? 34 35 /// an array of structs 36 var ingredients \[ingredient] 37 38 /// an array of strings 39 var sideoptions \[string] 40 41 /// a dictionary property 42 var nutritionalinfo \[string string] 43 44 /// a date type property 45 var releasedate date? 46 } ก่อนที่จะเก็บตัวอย่างของวัตถุนี้ในฐานข้อมูล back4app คุณสมบัติทั้งหมดต้องสอดคล้องกับโปรโตคอล codable และ hashable เราจะใช้วิธีการต่อไปนี้ในการจัดการวัตถุเหล่านี้ในฐานข้อมูล back4app create //the procedure for reading and updating a recipe object is similar since they rely on the save() method how a recipe is instantiated determines if we are creating or updating the object on the back4app database when creating a new instance we use 1 var newrecipe recipe 2 3 // setup newrecipe's properties 4 newrecipe name = "my recipe's name" 5 newrecipe servings = 4 6 newrecipe price = 3 99 7 newrecipe isavailable = false 8 newrecipe category = breakfast 9 newrecipe sideoptions = \["juice"] 10 newrecipe releasedate = date() 11 12 13 // saves newrecipe on your back4app database synchronously and returns the new saved item it throws and error if something went wrong 14 let savedrecipe = try? savedrecipe save() 15 16 // saves savedrecipe on your back4app database asynchronously, and passes a result\<todolistitem, parseerror> object to the completion block to handle the save proccess 17 savedrecipe save { result in 18 // handle the result to check the save was successfull or not 19 } update //and to update an existing instance, we have to provide the objectid value which identifies the the object on the back4app database a satandard update can be implemented in the following way 1 let recipetoupdate = recipe(objectid "object id") 2 3 // update the properties you need 4 recipetoupdate name = "my updated recipe's name" 5 recipetoupdate servings = 5 6 recipetoupdate price = 5 99 7 recipetoupdate isavailable = true 8 recipetoupdate category = lunch 9 recipetoupdate sideoptions = \["juice", "coffee"] 10 recipetoupdate releasedate = date() addingtimeinterval(3600 24) 11 12 13 // save changes synchronousty 14 try? recipetoupdate save() 15 16 // or save changes asynchronously 17 recipetoupdate save { result in 18 // handle the result 19 } read //for reading objects stored on your back4app database, recipe now provides the query() static method which returns a query\<recipe> this query object can be constructed using one or more queryconstraint objects in the following way 1 let query = recipe query() // a query to fetch all recipe items on your back4app database 2 let query = recipe query("name" == "omelette") // a query to fetch all recipe items with name "omelette" on your back4app database 3 let query = recipe query(\["name" == "omelette", "price" = 9 99]) // a query to fetch all recipe items with name = "omelette" and price = 9 99 4 5 // fetches the items synchronously or throws an error if found 6 let fetchedrecipes = try? query find() 7 8 // fetches the items asynchronously and calls a completion block passing a result object containing the result of the operation 9 query find { result in 10 // handle the result 11 } delete //any deletion process is performed by calling the method delete() on the object to be deleted 1 var recipetodelete recipe 2 3 // delete recipetodelete synchronously 4 try? recipetodelete delete() 5 6 // delete recipetodelete asynchronously 7 recipetodelete delete { result in 8 // handle the result 9 } 1 สร้างเทมเพลตแอปสูตร เราจะเริ่มต้นด้วยการสร้างโปรเจ็กต์ xcode ใหม่ ในบทแนะนำนี้โปรเจ็กต์ควรมีลักษณะดังนี้ คุณสามารถเข้าถึงโครงการทั้งหมดได้ตลอดเวลาผ่านที่เก็บ github ของเรา ที่เก็บตัวอย่าง ios ไปที่ xcode และค้นหาไฟล์ scenedelegate swift เพื่อเพิ่มแถบนำทางด้านบนของแอป เราจะตั้งค่า uinavigationcontroller เป็น root view controller ในลักษณะดังต่อไปนี้ 1 class scenedelegate uiresponder, uiwindowscenedelegate { 2 3 var window uiwindow? 4 5 func scene( scene uiscene, willconnectto session uiscenesession, options connectionoptions uiscene connectionoptions) { 6 guard let scene = (scene as? uiwindowscene) else { return } 7 8 window = init(windowscene scene) 9 window? rootviewcontroller = uinavigationcontroller(rootviewcontroller recipescontroller()) 10 window? makekeyandvisible() 11 12 // additional logic 13 } 14 15 16 } คลาส root view controller (recipescontroller) สำหรับ navigation controller เป็นซับคลาสของ uiviewcontroller ซึ่งเราจะจัดรูปแบบฟอร์มเพื่อสร้างและอัปเดตวัตถุ recipe บน back4app database 2 ตั้งค่าตัววัตถุ recipe วัตถุที่คุณต้องการบันทึกใน back4app database ของคุณต้องปฏิบัติตามโปรโตคอล parseobject ในแอป recipes ของเรา วัตถุนี้คือ recipe ดังนั้นคุณต้องสร้างวัตถุนี้ก่อน สร้างไฟล์ใหม่ชื่อ recipe swift และเพิ่มสิ่งต่อไปนี้ 1 import foundation 2 import parseswift 3 4 struct recipe parseobject { 5 /// enumeration for the recipe category 6 enum category int, caseiterable, codable { 7 case breakfast = 0, lunch = 1, dinner = 2 8 9 var title string { 10 switch self { 11 case breakfast return "breakfast" 12 case lunch return "lunch" 13 case dinner return "dinner" 14 } 15 } 16 } 17 18 // required properties from parseobject protocol 19 var objectid string? 20 var createdat date? 21 var updatedat date? 22 var acl parseacl? 23 24 /// a string type property 25 var name string? 26 27 /// an integer type property 28 var servings int? 29 30 /// a double (or float ) type property 31 var price double? 32 33 /// a boolean type property 34 var isavailable bool? 35 36 /// an enumeration type property 37 var category category? 38 39 /// an array of structs 40 var ingredients \[ingredient] 41 42 /// an array of strings 43 var sideoptions \[string] 44 45 /// a dictionary property 46 var nutritionalinfo \[string string] 47 48 /// a date type property 49 var releasedate date? 50 51 /// maps the nutritionalinfo property into an array of tuples 52 func nutritionalinfoarray() > \[(name string, value string)] { 53 return nutritionalinfo map { ($0 key, $0 value) } 54 } 55 } ที่ซึ่งเราได้เพิ่มคุณสมบัติที่จำเป็นทั้งหมดให้กับ recipe ตามตารางคุณสมบัติของสูตรอาหารแล้ว ประเภทข้อมูลส่วนผสมเป็นโครงสร้างที่เก็บปริมาณและคำอธิบายของส่วนผสม ตามที่กล่าวไว้ก่อนหน้านี้ ประเภทข้อมูลนี้ควรปฏิบัติตามโปรโตคอล codable และ hashable เพื่อเป็นส่วนหนึ่งของคุณสมบัติของสูตรอาหาร 1 import foundation 2 3 struct ingredient hashable, codable { 4 var quantity float 5 var description string 6 } นอกจากนี้ คุณสมบัติหมวดหมู่ในสูตรอาหารมีการกำหนดประเภทข้อมูลเป็นการจัดหมวดหมู่ (category) ซึ่งยังปฏิบัติตามโปรโตคอลที่เกี่ยวข้อง 1 struct recipe parseobject { 2 /// enumeration for the recipe category 3 enum category int, caseiterable, codable { 4 case breakfast = 0, lunch = 1, dinner = 2 5 6 7 } 8 9 } 3 การตั้งค่า recipescontroller ใน recipescontroller เราควรดำเนินการกำหนดค่าที่จำเป็นทั้งหมดสำหรับ navigationbar และแบบฟอร์มที่ใช้ในการบันทึกคุณสมบัติของสูตรอาหารทั้งหมด บทเรียนนี้ไม่ครอบคลุมวิธีการดำเนินการจัดรูปแบบสำหรับแบบฟอร์ม เราจึงมุ่งเน้นไปที่ตรรกะที่เกี่ยวข้องกับการจัดการประเภทข้อมูลโดยใช้ parseswift sdk ด้านล่างนี้เราจะเน้นจุดสำคัญใน recipescontroller ซึ่งช่วยให้เราเข้าใจวิธีการเชื่อมต่อระหว่างส่วนติดต่อผู้ใช้และข้อมูลที่มาจากฐานข้อมูล back4app ของคุณ 1 class recipescontroller uiviewcontroller { 2 enum previousnext int { case previous = 0, next = 1 } 3 4 5 6 var recipes \[recipe] = \[] // 1 an array of recipes fetched from your back4app database 7 8 // section header labels 9 private let recipelabel uilabel = titlelabel(title "recipe overview") 10 private let ingredientslabel uilabel = titlelabel(title "ingredients") 11 private let nutritionalinfolabel uilabel = titlelabel(title "nutritional information") 12 13 // 2 a custom view containing input fields to enter the recipe's information (except nutritional info and ingredients) 14 let recipeoverviewview recipeinfoview 15 16 // 3 a stack view containig the fields to enter the recipe's ingredients 17 let ingredientsstackview uistackview 18 19 // 4 a stack view containig the fields to enter the nutritional information 20 let nutritionalinfostackview uistackview 21 22 // 5 buttons to handle the crud logic for the recipe object currently displayed 23 private var savebutton uibutton = uibutton(title "save") 24 private var updatebutton uibutton = uibutton(title "update") 25 private var reloadbutton uibutton = uibutton(title "reload") 26 27 var currentrecipeindex int? // 6 an integer containing the index of the current recipe presenten from the recipes property 28 29 override func viewdidload() { 30 super viewdidload() 31 setupnavigationbar() 32 setupviews() 33 } 34 35 override func viewdidappear( animated bool) { 36 super viewdidappear(animated) 37 handlereloadrecipes() 38 } 39 40 private func setupnavigationbar() { 41 navigationcontroller? navigationbar bartintcolor = primary 42 navigationcontroller? navigationbar titletextattributes = \[ foregroundcolor uicolor white] 43 navigationcontroller? navigationbar istranslucent = false 44 navigationcontroller? navigationbar barstyle = black 45 navigationitem title = "parse data types" uppercased() 46 } 47 48 private func setupviews() { 49 // see the project example for more details 50 51 savebutton addtarget(self, action #selector(handlesaverecipe), for touchupinside) 52 updatebutton addtarget(self, action #selector(handleupdaterecipe), for touchupinside) 53 reloadbutton addtarget(self, action #selector(handlereloadrecipes), for touchupinside) 54 } 55 56 57 } 3 การจัดการข้อมูลที่ผู้ใช้ป้อนและการแยกวัตถุสูตรอาหาร ในไฟล์แยกต่างหาก (ชื่อ recipescontroller+parseswiftlogic swift) โดยใช้ส่วนขยาย เราจะดำเนินการวิธีการ handlesaverecipe(), handleupdaterecipe() และ handleupdaterecipe() เพื่อจัดการกับข้อมูลที่ป้อน 1 import uikit 2 import parseswift 3 4 extension recipescontroller { 5 /// retrieves all the recipes stored on your back4app database 6 @objc func handlereloadrecipes() { 7 view\ endediting(true) 8 let query = recipe query() 9 query find { \[weak self] result in // retrieves all the recipes stored on your back4app database and refreshes the ui acordingly 10 guard let self = self else { return } 11 switch result { 12 case success(let recipes) 13 self recipes = recipes 14 self currentrecipeindex = recipes isempty ? nil 0 15 self setuprecipenavigation() 16 17 dispatchqueue main async { self presentcurrentrecipe() } 18 case failure(let error) 19 dispatchqueue main async { self showalert(title "error", message error message) } 20 } 21 } 22 } 23 24 /// called when the user wants to update the information of the currently displayed recipe 25 @objc func handleupdaterecipe() { 26 view\ endediting(true) 27 guard let recipe = preparerecipemetadata(), recipe objectid != nil else { // prepares the recipe object for updating 28 return showalert(title "error", message "recipe not found ") 29 } 30 31 recipe save { \[weak self] result in 32 switch result { 33 case success(let newrecipe) 34 self? recipes append(newrecipe) 35 self? showalert(title "success", message "recipe saved on your back4app database! (objectid \\(newrecipe id)") 36 case failure(let error) 37 self? showalert(title "error", message "failedto save recipe \\(error message)") 38 } 39 } 40 } 41 42 /// saves the currently displayed recipe on your back4app database 43 @objc func handlesaverecipe() { 44 view\ endediting(true) 45 guard var recipe = preparerecipemetadata() else { // prepares the recipe object for storing 46 return showalert(title "error", message "failed to retrieve all the recipe fields ") 47 } 48 49 recipe objectid = nil // when saving a recipe object, we ensure it will be a new instance of it 50 recipe save { \[weak self] result in 51 switch result { 52 case success(let newrecipe) 53 if let index = self? currentrecipeindex { self? recipes\[index] = newrecipe } 54 self? showalert(title "success", message "recipe saved on your back4app database! (objectid \\(newrecipe id))") 55 case failure(let error) 56 self? showalert(title "error", message "failed to save recipe \\(error message)") 57 } 58 } 59 } 60 61 /// when called it refreshes the ui according to the content of recipes and currentrecipeindex properties 62 private func presentcurrentrecipe() { 63 64 } 65 66 /// adds the 'next recipe' and 'previous recipe' button on the navigation bar these are used to iterate over all the recipes retreived from your back4app database 67 private func setuprecipenavigation() { 68 69 } 70 71 /// reads the information the user entered via the form and returns it as a recipe object 72 private func preparerecipemetadata() > recipe? { 73 let ingredientscount = ingredientsstackview\ arrangedsubviews count 74 let nutritionalinfocount = nutritionalinfostackview\ arrangedsubviews count 75 76 let ingredients \[ingredient] = (0 \<ingredientscount) compactmap { row in 77 guard let textfields = ingredientsstackview\ arrangedsubviews\[row] as? doubletextfield, 78 let quantitystring = textfields primarytext, 79 let quantity = float(quantitystring), 80 let description = textfields secondarytext 81 else { 82 return nil 83 } 84 return ingredient(quantity quantity, description description) 85 } 86 87 var nutritionalinfo \[string string] = \[ ] 88 89 (0 \<nutritionalinfocount) foreach { row in 90 guard let textfields = nutritionalinfostackview\ arrangedsubviews\[row] as? doubletextfield, 91 let content = textfields primarytext, !content isempty, 92 let value = textfields secondarytext, !value isempty 93 else { 94 return 95 } 96 nutritionalinfo\[content] = value 97 } 98 99 let recipeinfo = recipeoverviewview\ parseinputtorecipe() // reads all the remaining fields from the form (name, category, price, serving, etc) and returns them as a tuple 100 101 // we collect all the information the user entered and create an instance of recipe 102 // the recipeinfo objectid will be nil if the currently displayed information does not correspond to a recipe already saved on your back4app database 103 let newrecipe recipe = recipe( 104 objectid recipeinfo objectid, 105 name recipeinfo name, 106 servings recipeinfo servings, 107 price recipeinfo price, 108 isavailable recipeinfo isavailable, 109 category recipeinfo category, 110 ingredients ingredients, 111 sideoptions recipeinfo sideoptions, 112 nutritionalinfo nutritionalinfo, 113 releasedate recipeinfo releasedate 114 ) 115 116 return newrecipe 117 } 118 119 /// called when the user presses the 'previous recipe' or 'next recipe' button 120 @objc private func handleswitchrecipe(button uibarbuttonitem) { 121 122 } 123 } 4 รันแอป! ก่อนกดปุ่มรันใน xcode อย่าลืมตั้งค่าการใช้งาน back4app ของคุณในคลาส appdelegate! ครั้งแรกที่คุณรันโปรเจกต์ คุณควรเห็นอะไรบางอย่างเช่นนี้ในซิมูเลเตอร์ (โดยที่ฟิลด์ทั้งหมดว่างเปล่า) ตอนนี้คุณสามารถเริ่มป้อนสูตรอาหารเพื่อบันทึกลงในฐานข้อมูล back4app ของคุณได้แล้ว เมื่อคุณบันทึกสูตรอาหารหนึ่งสูตรแล้ว ให้ไปที่ แดชบอร์ด back4app https //parse dashboard back4app com/apps และไปที่แอปพลิเคชันของคุณ ในส่วนฐานข้อมูล คุณจะพบคลาส recipe ซึ่งมีสูตรอาหารทั้งหมดที่สร้างโดยแอป ios โดยเฉพาะอย่างยิ่ง ควรสังเกตว่าประเภทข้อมูลที่ไม่เป็นพื้นฐาน เช่น ส่วนผสม, หมวดหมู่สูตร หรือพจนานุกรม ถูกเก็บรักษาอย่างไร หากคุณนำทางผ่านข้อมูลที่บันทึกไว้ภายใต้คลาส recipe คุณจะพบว่า พจนานุกรม nutritionalinformation ถูกเก็บเป็นวัตถุ json อาร์เรย์ \[ingredients] ถูกเก็บเป็นอาร์เรย์ของวัตถุ json การจัดประเภท recipe category เนื่องจากมีประเภทข้อมูลเป็นจำนวนเต็มในฐานะ rawvalue จึงถูกแปลงเป็นประเภทค่าหมายเลข คุณสมบัติ releasedate ซึ่งเป็นค่าประเภท date ใน swift , ก็ถูกเก็บเป็นค่าประเภท date เช่นกัน เพื่อสรุป เมื่อดึงข้อมูลจากฐานข้อมูล back4app ของคุณ คุณไม่จำเป็นต้องถอดรหัสฟิลด์ทั้งหมดเหล่านี้ด้วยตนเอง parseswift sdk จะถอดรหัสให้โดยอัตโนมัติ นั่นหมายความว่า เมื่อสร้างคำค้น (query\<recipe> ในกรณีนี้) เพื่อดึงข้อมูล วิธี query find() จะทำการแยกประเภทข้อมูลและวัตถุ json ทั้งหมดเพื่อคืนค่าอาร์เรย์ recipe โดยไม่มีขั้นตอนการแยกประเภทเพิ่มเติมที่ต้องดำเนินการ