使用swift和market查找附近的酒吧

问题描述 投票:0回答:2

我有这段代码,我想保存从阵列中的MKLocalSearch获得的位置,所以我可以在以后使用它们。你有什么想法我能做到吗?

func searchForBarsAndRestaurants(searchFor: String){
    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = typeOfPlace   //or whatever you're searching for

    request.region = MKCoordinateRegionMakeWithDistance(location.coordinate, 300, 300)


    let search = MKLocalSearch(request: request)
    search.start { response, error in
        guard let response = response
        else {
            print("There was an error searching for: \(String(describing: request.naturalLanguageQuery)) error: \(String(describing: error))")
            return
        }

        print(response.mapItems.count)
        print("There are \(response.mapItems.count)" , searchFor)
        for item in response.mapItems {
            // You may be able to match the address to what the geoCode gives you
            // or present the user with a list of options
            print("\(String(describing: item.name))")
            var totalDistances: Array<Double> = Array()
            let distance = self.location.distance(from: item.placemark.location!)
            totalDistances += [distance]
            print("distance is " ,distance)
            print(totalDistances.count)
        }
    }
}
ios swift xcode mapkit mklocalsearch
2个回答
0
投票

您需要将totalDistances定义为Class Property。

var totalDistances: Array<Double> = Array()

func searchForBarsAndRestaurants(searchFor: String){
    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = typeOfPlace   //or whatever you're searching for

    request.region = MKCoordinateRegionMakeWithDistance(location.coordinate, 300, 300)


    let search = MKLocalSearch(request: request)
    search.start { response, error in
        guard let response = response
        else {
            print("There was an error searching for: \(String(describing: request.naturalLanguageQuery)) error: \(String(describing: error))")
            return
        }

        print(response.mapItems.count)
        print("There are \(response.mapItems.count)" , searchFor)
        for item in response.mapItems {
            // You may be able to match the address to what the geoCode gives you
            // or present the user with a list of options
            print("\(String(describing: item.name))")
            let distance = self.location.distance(from: item.placemark.location!)
            self.totalDistances += [distance]
            print("distance is " ,distance)
            print(self.totalDistances.count)
        }
    }
}

1
投票

当然,你只需要使用单身人士。

你想要的是使用全局变量。这是一个如何做到这一点的例子,w

let sharedNetworkManager = NetworkManager(baseURL: API.baseURL)

class NetworkManager {

    // MARK: - Properties

    let baseURL: URL

    // Initialization

    init(baseURL: URL) {
        self.baseURL = baseURL
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.