ios - 在ios swift中实现地址搜索

标签 ios swift geolocation uisearchbar

我需要实现一个屏幕,我的 ios 应用程序将在其中确定我当前的位置并将其地理编码到文本字段。我可以在 ios 中使用 CLLocationManager 来做到这一点。 用户还可以在搜索栏中输入他的其他地址,应用程序现在应该显示所有匹配的地址。您能帮助我如何实现第二个要求吗? 谢谢!

最佳答案

与我在使用 Google API 的项目中遵循的概念相同

Google API:
https://maps.googleapis.com/maps/api/place/details/json?placeid=\(searchString.text)&key=(YOUR_API_KEY)" 

首先,我们需要为您的文本字段添加功能

override func viewDidLoad() {
        super.viewDidLoad()
searchString.addTarget(self, action: "whiletyping:", forControlEvents: UIControlEvents.EditingChanged)
}



func whiletyping(textField:UITextField)
    {
        getPlaces(searchString.text)
    }

func getPlaces(searchString: String) {
        var request = requestForSearch(searchString)
        println("the URL :\(request)")

        var session = NSURLSession.sharedSession()
        var task = session.dataTaskWithRequest(request) { data, response, error in
            self.handleResponse(data, response: response as? NSHTTPURLResponse, error: error)

            println("the response : \(response)")
        }

        task.resume()
    }

    func handleResponse(data: NSData!, response: NSHTTPURLResponse!, error: NSError!) {
        if let error = error {
            println("GooglePlacesAutocomplete Error: \(error.localizedDescription)")
            return
        }

        if response == nil {
            println("GooglePlacesAutocomplete Error: No response from API")
            return
        }

        if response.statusCode != 200 {
            println("GooglePlacesAutocomplete Error: Invalid status code \(response.statusCode) from API")
            return
        }

        var serializationError: NSError?
        var json: NSDictionary = NSJSONSerialization.JSONObjectWithData(
            data,
            options: NSJSONReadingOptions.MutableContainers,
            error: &serializationError
            ) as! NSDictionary

        if let error = serializationError {
            println("GooglePlacesAutocomplete Error: \(error.localizedDescription)")
            return
        }

        // Perform table updates on UI thread
        dispatch_async(dispatch_get_main_queue(), {
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false

            if let predictions = json["predictions"] as? Array<AnyObject> {
                self.places = predictions.map { (prediction: AnyObject) -> Place2 in
                    return Place2(
                        id: prediction["id"] as! String,
                        description: prediction["description"] as! String,
                        place_id: prediction["place_id"] as! String
                    )
                }


            }
        })
    }


    func requestForSearch(searchString: String) -> NSURLRequest {
        let params = [
            "input": searchString,
            "type": "(\(placeType.description))",
            //"type": "",
            "key": "**YOUR API KEY**"
        ]

        return NSMutableURLRequest(
            URL: NSURL(string: "https://maps.googleapis.com/maps/api/place/autocomplete/json?\(query(params))")!
        )
    }

    func query(parameters: [String: AnyObject]) -> String {
        var components: [(String, String)] = []
        for key in sorted(Array(parameters.keys), <) {
            let value: AnyObject! = parameters[key]

            components += [(escape(key), escape("\(value)"))]
        }

        return join("&", components.map{"\($0)=\($1)"} as [String])
    }

    func escape(string: String) -> String {
        let legalURLCharactersToBeEscaped: CFStringRef = ":/?&=;+!@#$()',*"

         //return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue)

        return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String

    }

输出:

let place = self.places[0]
address1=place.description

place = self.places[1]
address2=place.description

place = self.places[2]
address3=place.description

place = self.places[3]
address4=place.description

place = self.places[4]
address5=place.description

关于ios - 在ios swift中实现地址搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31314712/

相关文章:

ios - 如何在不导航所有层次结构的情况下测试我的应用程序中的特定屏幕

javascript - Google Maps API V3 - 在边界内最近的路线

javascript - 如何在 python 中制作 HTML5 Geolocation 对象?

iPhone - 按纬度和经度划分的 SQLite 距离

ios - 在 IOS 中从国家名称获取国家代码

objective-c - 自动将文件复制到App Document文件夹

json - 我如何快速将 JSON 解码为一个类?

ios - 在 iOS 中,如何从正在运行的应用程序内部获取当前 CPU 利用率?

ios - nineveh vs cocos3d

ios - XC测试 : Can not get the last collection cell element after swipeLeft()