以下のコードにある \(location.name)
、 \(location.address)
をgemini AIを使って建物について Text("番号: \(location.phoneNumber)")
の下に表示したいのですが、上手くできませんでした。
xcodeのパッケージで generative-ai-swift をインストールしてます。
Gemini AIについては以下の記事を参考にしています。
【初心者向け】iPad だけで Google の AI モデル「Gemini」を使ったアプリを作ってみよう! - Qiita
どなたかこのコードでGemini AIを使って動かせるコードを教えて頂きたいです。
appid=
はAPIキーになっているのでXで伏せさせてください。
import SwiftUI
import CoreLocation
import MapKit
struct LocationInfo {
var id = UUID()
var name: String
var address: String
var phoneNumber: String
var coordinates: String
var locat12: String
var locat23: String
var locat25: String
init(name: String, address: String, phoneNumber: String, coordinates: String, locat12: String, locat23: String, locat25: String) {
self.name = name
self.address = address
self.phoneNumber = phoneNumber
self.coordinates = coordinates
self.locat12 = locat12
self.locat23 = locat23
self.locat25 = locat25
}
}
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate, XMLParserDelegate {
var region = MKCoordinateRegion()
var latitude: Double = 0.0
var longitude: Double = 0.0
var selectedCategory = "0401"
var locations: [LocationInfo] = []
var isReadingFeatureName = false
var shouldSkip = false
var locat12: String = ""
var locat23: String = ""
var locat25: String = ""
var locat1: String = ""
var currentCoordinates: String = ""
private let locationManager = CLLocationManager()
var currentElement: String = ""
var currentiName: String = ""
var currentAddress: String = ""
var currentPhoneNumber: String = ""
var currentLatitude: String = ""
var currentLongitude: String = ""
var latitude21: String = ""
var longitude21: String = ""
override init() {
super.init()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
func fetchData2() {
let urlString = "https://map.yahooapis.jp/placeinfo/V1/get?lat=\(latitude)&lon=\(longitude)&appid=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
if let url = URL(string: urlString) {
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data, let xmlString = String(data: data, encoding: .utf8) {
DispatchQueue.main.async {
self.parseXML1(xmlString: xmlString)
}
}
}
task.resume()
}
}
func parseXML1(xmlString: String) {
guard let data = xmlString.data(using: .utf8) else {
print("Failed to convert XML string to data.")
return
}
let parser = XMLParser(data: data)
parser.delegate = self
if parser.parse() {
print("XML parsing 成功.")
objectWillChange.send()
} else {
print("XML parsing エラー.")
}
}
func fetchData() {
let urlString = "https://map.yahooapis.jp/search/local/V1/localSearch?appid=xxxxxxxxxxxxxxxxx&gc=\(selectedCategory)&lat=\(latitude)&lon=\(longitude)&sort=geno"
if let url = URL(string: urlString) {
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data, let xmlString = String(data: data, encoding: .utf8) {
DispatchQueue.main.async {
self.parseXML(xmlString: xmlString)
}
}
}
task.resume()
}
}
func parseXML(xmlString: String) {
locations.removeAll()
guard let data = xmlString.data(using: .utf8) else {
print("Failed to convert XML string to data.")
return
}
let parser = XMLParser(data: data)
parser.delegate = self
if parser.parse() {
print("XML parsing 成功.")
objectWillChange.send()
} else {
print("XML parsing エラー.")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
self.region = MKCoordinateRegion(center: location.coordinate, span: span)
self.latitude = location.coordinate.latitude
self.longitude = location.coordinate.longitude
}
}
var excludedElements: Set<String> = ["Property", "Country", "Genre", "Station"]
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String] = [:]) {
currentElement = elementName
if elementName == "Feature" {
isReadingFeatureName = true
shouldSkip = false // <Feature>
}
if shouldSkip {
return
}
if elementName == "Geometry" {
shouldSkip = true
return
}
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
let trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmedString.isEmpty {
switch currentElement {
case "Name":
if isReadingFeatureName && !shouldSkip {
currentiName = trimmedString
}
case "Address":
currentAddress = trimmedString
locat1 = currentAddress
case "Coordinates":
let coordinatesComponents = trimmedString.components(separatedBy: ",")
if coordinatesComponents.count == 2,
let latitude21 = Double(coordinatesComponents[0]),
let longitude21 = Double(coordinatesComponents[1]) {
currentLatitude = "\(latitude21)"
currentLongitude = "\(longitude21)"
locat25 = currentLatitude
locat23 = currentLongitude
}
case "Tel1":
currentPhoneNumber = trimmedString
default:
break
}
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == "Feature" {
let location = LocationInfo(
name: currentiName,
address: currentAddress,
phoneNumber: currentPhoneNumber,
coordinates: "\(locat23), \(locat25)",
locat12: locat12,
locat23: locat23,
locat25: locat25
)
locations.append(location)
}
}
}
struct ContentView: View {
@ObservedObject var locationManager = LocationManager()
@State private var isSearching = false
var body: some View {
NavigationView {
VStack {
Picker("Category", selection: $locationManager.selectedCategory) {
Text("病院").tag("0401")
Text("福祉施設").tag("0404")
}
.pickerStyle(SegmentedPickerStyle())
.frame(width: 200, alignment: .center)
.font(.system(size: 14))
Button(action: {
print("Search button pressed")
locationManager.fetchData()
locationManager.fetchData2() // Call fetchData2
isSearching = true
}) {
Text("検索")
}
if isSearching {
List {
Text("現在地: \(locationManager.locat1)") // Display locat1
.font(.headline)
.padding(.top, 10)
.padding(.bottom, 20)
ForEach(locationManager.locations, id: \.id) { location in
NavigationLink(destination: LocationDetail(location: location)) {
LocationRow(location: location)
}
}
}
}
}
.navigationTitle("位置情報")
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct LocationRow: View {
var location: LocationInfo
var body: some View {
VStack(alignment: .leading) {
Text("\(location.name)")
.font(.headline)
Text("\(location.address)")
.font(.subheadline)
}
}
}
struct LocationDetail: View {
var location: LocationInfo
var body: some View {
VStack {
Text("\(location.name)")
.font(.headline)
Text("住所: \(location.address)")
Text("番号: \(location.phoneNumber)")
Map(coordinateRegion: .constant(MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: Double(location.locat23) ?? 0.0, longitude: Double(location.locat25) ?? 0.0),
span: MKCoordinateSpan(latitudeDelta: 0.001, longitudeDelta: 0.001)
)))
.frame(width: 400,height: 400)
.cornerRadius(10)
.overlay(
Marker(coordinate: CLLocationCoordinate2D(latitude: Double(location.locat23) ?? 0.0, longitude: Double(location.locat25) ?? 0.0), tint: .red)
)
}
.navigationTitle("詳細")
}
}
struct Marker: View {
var coordinate: CLLocationCoordinate2D
var tint: Color
var body: some View {
Image(systemName: "mappin.circle.fill")
.resizable()
.frame(width: 30, height: 30)
.foregroundColor(tint)
.offset(x: 0, y: -15) //
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}