iOS
...
Data Objects
Eseguire Geoquery con ParseSwift SDK per iOS
9 min
geoquery introduzione utilizziamo il termine geoquery per riferirci al tipo di query in cui le loro condizioni coinvolgono parsegeopoint parsegeopoint campi di tipo si consiglia di utilizzare la parsegeopoint parsegeopoint struttura per memorizzare i dati sulla posizione geografica in un database back4app il parseswift sdk parseswift sdk fornisce un insieme di metodi che ci consente di interrogare i dati in base alle condizioni applicate ai parsegeopoint parsegeopoint di tipo di dati prerequisiti per completare questo tutorial, avrai bisogno di un'app https //www back4app com/docs/get started/new parse app un'app ios di base per testare le query obiettivo comprendere come interrogare i dati utilizzando condizioni sui dati sulla posizione geografica 1 rassegna rapida sulla query\<u> classe qualsiasi query eseguita su un database back4app viene effettuata tramite la classe generica query\<u> query\<u> il parametro generico u u (che conforma al parseobject parseobject protocollo) è il tipo di dati degli oggetti che stiamo cercando di recuperare dal database dato un tipo di dato come myobject myobject , recuperiamo questi oggetti da un database back4app nel seguente modo 1 import parseswift 2 3 struct myobject parseobject { 4 5 } 6 7 let query = myobject query() 8 9 // executes the query asynchronously 10 query find { result in 11 // handle the result (of type result<\[myobject], parseerror>) 12 } puoi leggere di piĂą sulla query\<u> query\<u> classe https //github com/parse community/parse swift 2 salva alcuni dati su back4app prima di iniziare a eseguire query, dovremmo memorizzare alcuni dati di esempio su un database back4app seguendo la https //www back4app com/docs/ios/parse swift sdk/install sdk , puoi configurare e collegare la tua app ios di esempio al tuo database back4app per questa guida, memorizzeremo informazioni sulle cittĂ utilizziamo la seguente struct per organizzare le informazioni di una cittĂ 1 import parseswift 2 3 struct city parseobject { 4 5 6 var name string? // city's name 7 var location parsegeopoint? // it will store the city's coordinate on earth 8 } ora procediamo a memorizzare i dati di esempio questo passaggio può essere implementato utilizzando swift o direttamente dalla https //www youtube com/watch?v=nvwryrzbcma sulla piattaforma back4app //after setting up your xcode project, calling the following method should save some sample data on your back4app database 1 import parseswift 2 3 func setupsampledata() { 4 do { 5 // montevideo uruguay 6 = try city( 7 name "montevideo", 8 location parsegeopoint(coordinate cllocationcoordinate2d(latitude 34 85553195363169, longitude 56 207280375137955)) 9 ) save() 10 11 // brasĂlia brazil 12 = try city( 13 name "brasĂlia", 14 location parsegeopoint(coordinate cllocationcoordinate2d(latitude 15 79485821477289, longitude 47 88391074690196)) 15 ) save() 16 17 // bogotá colombia 18 = try city( 19 name "bogotá", 20 location parsegeopoint(coordinate cllocationcoordinate2d(latitude 4 69139880891712, longitude 74 06936691331047)) 21 ) save() 22 23 // mexico city mexico 24 = try city( 25 name "mexico city", 26 location parsegeopoint(coordinate cllocationcoordinate2d(latitude 19 400977162618933, longitude 99 13311378164776)) 27 ) save() 28 29 // washington, d c united states 30 = try city( 31 name "washington, d c ", 32 location parsegeopoint(coordinate cllocationcoordinate2d(latitude 38 930727220189944, longitude 77 04626261880388)) 33 ) save() 34 35 // ottawa canada 36 = try city( 37 name "ottawa", 38 location parsegeopoint(latitude 45 41102167733425, longitude 75 695414598736) 39 ) save() 40 } catch let error as parseerror { 41 print("\[parseswift error]", error message) 42 } catch { 43 print("\[error]", error localizeddescription) 44 } 45 } back4app's console //a quick way to insert elements on your back4app database is via the console located in your app’s api section once you are there, you can start running javascript code to save the sample data 1 // add city objects and create table 2 // note how geopoints are created, passing latitude and longitude as arguments 3 // montevideo 4 city = new parse object('city'); 5 city set('name', 'montevideo uruguay'); 6 city set('location', new parse geopoint( 34 85553195363169, 56 207280375137955)); 7 await city save(); 8 9 // brasĂlia 10 city = new parse object('city'); 11 city set('name', 'brasĂlia brazil'); 12 city set('location', new parse geopoint( 15 79485821477289, 47 88391074690196)); 13 await city save(); 14 15 // bogotá 16 city = new parse object('city'); 17 city set('name', 'bogotá colombia'); 18 city set('location', new parse geopoint(4 69139880891712, 74 06936691331047)); 19 await city save(); 20 21 // mexico city 22 city = new parse object('city'); 23 city set('name', 'mexico city mexico'); 24 city set('location', new parse geopoint(19 400977162618933, 99 13311378164776)); 25 await city save(); 26 27 // washington, d c 28 city = new parse object('city'); 29 city set('name', 'washington, d c usa'); 30 city set('location', new parse geopoint(38 930727220189944, 77 04626261880388)); 31 await city save(); 32 33 // ottawa 34 city = new parse object('city'); 35 city set('name', 'ottawa canada'); 36 city set('location', new parse geopoint(45 41102167733425, 75 695414598736)); 37 await city save(); 3 interrogare i dati ordinare i risultati con i dati di esempio salvati, possiamo iniziare a eseguire diversi tipi di query per il nostro primo esempio, selezioneremo tutte le cittĂ e le ordineremo in base alla distanza da un geopunto di riferimento implementiamo questa query passando un vincolo all' query\<city> query\<city> oggetto il metodo near(key\ geopoint ) near(key\ geopoint ) disponibile tramite il parseswift sdk parseswift sdk ci consente di costruire tale vincolo come argomenti, passiamo il nome del campo (di solito chiamato key key ) contenente il riferimento geopoint geopoint 1 // the reference geopoint will be kingston city jamaica 2 guard let kingstongeopoint = try? parsegeopoint(latitude 18 018086950599134, longitude 76 79894232253473) else { return } 3 4 let query = city query(near(key "location", geopoint kingstongeopoint)) // the method near(key\ geopoint ) returns the constraint needed to sort the query 5 6 let sortedcities \[city]? = try? query find() // executes the query synchronosuly and returns an array containing the cities properly sorted 7 8 query find { result in // executes the query asynchronosuly and returns a result<\[city], parseerror> type object to handle the results 9 switch result { 10 case success(let cities) 11 // cities = \[bogotá, washington dc, mexico city, ottawa, brasĂlia, montevideo] 12 case failure(let error) 13 // handle the error if something happened 14 } 15 } selezionare risultati all'interno di una determinata regione supponiamo di voler selezionare cittĂ all'interno di una certa regione possiamo ottenere questo con un vincolo creato dal metodo withinkilometers(key\ geopoint\ distance ) withinkilometers(key\ geopoint\ distance ) come argomenti, passiamo il nome del campo che contiene la posizione della cittĂ , il centro della regione (un parsegeopoint parsegeopoint di tipo di dato) e la distanza massima (in km ) che una cittĂ può essere da questo centro regionale per selezionare tutte le cittĂ che sono al massimo 3000km lontane da kingston giamaica, possiamo farlo nel seguente modo 1 let distance double = 3000 // km 2 guard let kingstongeopoint = try? parsegeopoint(latitude 18 018086950599134, longitude 76 79894232253473) else { return } 3 4 let query = city query(withinkilometers(key "location", geopoint kingstongeopoint, distance distance)) 5 // the method withinkilometers(key\ geopoint\ distance ) returns the constraint we need for this case 6 7 let sortedcities \[city]? = try? query find() // executes the query synchronosuly and returns an array containing the cities we are looking for (bogotá, washington dc and mexico city in this case) 8 9 query find { result in // executes the query asynchronosuly and returns a result<\[city], parseerror> type object to handle the results 10 switch result { 11 case success(let cities) 12 // cities = \[bogotá, washington dc, mexico city] 13 case failure(let error) 14 // handle the error if something happened 15 } 16 } inoltre, quando la distanza è espressa in miglia invece che in chilometri, possiamo utilizzare il withinmiles(key\ geopoint\ distance\ sorted ) withinmiles(key\ geopoint\ distance\ sorted ) metodo un metodo meno comune, withinradians(key\ geopoint\ distance\ sorted ) withinradians(key\ geopoint\ distance\ sorted ) , è anche disponibile se la distanza è espressa in radianti il suo utilizzo è molto simile ai metodi precedenti selezionare risultati all'interno di un dato poligono nell'esempio precedente, abbiamo selezionato cittĂ all'interno di una regione rappresentata da una regione circolare nel caso in cui richiediamo di avere una forma non circolare per la regione, il parseswift sdk parseswift sdk ci consente di costruire tali regioni a partire dai loro vertici ora, l'obiettivo di questo esempio è selezionare cittĂ all'interno di un poligono a cinque vertici questi vertici sono espressi utilizzando il parsegeopoint parsegeopoint struct una volta creati i vertici, istanziamo un parsepolygon parsepolygon questo poligono viene quindi passato al withinpolygon(key\ polygon ) withinpolygon(key\ polygon ) metodo (fornito dal parseswift sdk parseswift sdk ) per costruire il vincolo che ci permetterĂ di selezionare cittĂ all'interno di questo poligono 1 // the polygon where the selected cities are 2 let polygon parsepolygon? = { 3 do { 4 // we first instantiate the polygon vertices 5 let geopoint1 = try parsegeopoint(latitude 15 822238344514378, longitude 72 42845934415942) 6 let geopoint2 = try parsegeopoint(latitude 0 7433770196268968, longitude 97 44765968406668) 7 let geopoint3 = try parsegeopoint(latitude 59 997149373299166, longitude 76 52969196322749) 8 let geopoint4 = try parsegeopoint(latitude 9 488786415007201, longitude 18 346101586021952) 9 let geopoint5 = try parsegeopoint(latitude 15 414859532811047, longitude 60 00625459569375) 10 11 // next we compose the polygon 12 return try parsepolygon(\[geopoint1, geopoint2, geopoint3, geopoint4, geopoint5]) 13 } catch let error as parseerror { 14 print("failed to instantiate vertices \\(error message)") 15 return nil 16 } catch { 17 print("failed to instantiate vertices \\(error localizeddescription)") 18 return nil 19 } 20 }() 21 22 guard let safepolygon = polygon else { return } 23 24 let query = city query(withinpolygon(key "location", polygon safepolygon)) 25 // withinpolygon(key\ polygon ) returns the required constraint to apply on the query 26 27 let cities = try? query find() // executes the query synchronously 28 29 query find { result in // executes the query asynchronously and returns a result of type result<\[], parseerror> 30 // handle the result 31 } conclusione oggigiorno, eseguire operazioni sui dati di posizione per offrire servizi personalizzati è molto importante back4app insieme al parseswift sdk parseswift sdk rende facile implementare questo tipo di operazioni