在ios swift中实现地址搜索

时间:2015-07-09 10:24:36

标签: ios swift geolocation uisearchbar

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

1 个答案:

答案 0 :(得分:0)

我在使用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