如何从AddressDictionary获取格式化地址NSString?

时间:2011-10-21 10:42:00

标签: ios addressbook clgeocoder

尝试从AddressDictionary获取格式化地址,这是我从CLGeocoder获得的。 使用以下代码,但没有结果:

subtitle = [NSString stringWithString:[[addressDict objectForKey:@"FormattedAddressLines"]objectAtIndex:0]];

也尝试过:

subtitle = [[[ABAddressBook sharedAddressBook] formattedAddressFromDictionary:placemark.addressDictionary] string];

但此代码似乎仅适用于Mac OS X.

编译器询问ABAdressBook,但我导入了两个头文件。

#import <AddressBook/ABAddressBook.h>
#import <AddressBook/AddressBook.h>

10 个答案:

答案 0 :(得分:40)

addressDictionary属性的文档说:

  

您可以格式化此词典的内容以获取完整地址   字符串而不是自己构建地址。格式化   字典,使用ABCreateStringWithAddressDictionary函数作为   在地址簿UI函数参考中描述。

所以添加并导入AddressBookUI框架并尝试:

subtitle = 
    ABCreateStringWithAddressDictionary(placemark.addressDictionary, NO);

答案 1 :(得分:25)

在iOS 6.1下进行一些挖掘后,我发现CLPlacemark地址字典包含一个预先格式化的地址:

CLLocation *location = [[CLLocation alloc]initWithLatitude:37.3175 longitude:-122.041944];
[[[CLGeocoder alloc]init] reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
    CLPlacemark *placemark = placemarks[0];
    NSArray *lines = placemark.addressDictionary[ @"FormattedAddressLines"];
    NSString *addressString = [lines componentsJoinedByString:@"\n"];
    NSLog(@"Address: %@", addressString);
}];

我还没有找到关于此的文档,但它适用于我测试过的所有地址。

答案 2 :(得分:19)

正如Martyn Davis强调的那样,{9}中不推荐使用ABCreateStringWithAddressDictionary

您可以使用以下功能将addressDictionary转换为较新的CNMutablePostalAddress,然后使用CNPostalAddressFormatter生成本地化字符串,只要您导入Contacts即可框架。

Swift 3.x

// Convert to the newer CNPostalAddress
func postalAddressFromAddressDictionary(_ addressdictionary: Dictionary<NSObject,AnyObject>) -> CNMutablePostalAddress {
   let address = CNMutablePostalAddress()

   address.street = addressdictionary["Street" as NSObject] as? String ?? ""
   address.state = addressdictionary["State" as NSObject] as? String ?? ""
   address.city = addressdictionary["City" as NSObject] as? String ?? ""
   address.country = addressdictionary["Country" as NSObject] as? String ?? ""
   address.postalCode = addressdictionary["ZIP" as NSObject] as? String ?? ""

   return address
}

// Create a localized address string from an Address Dictionary
func localizedStringForAddressDictionary(addressDictionary: Dictionary<NSObject,AnyObject>) -> String {
    return CNPostalAddressFormatter.string(from: postalAddressFromAddressDictionary(addressDictionary), style: .mailingAddress)
}

Swift 2.x

import Contacts

// Convert to the newer CNPostalAddress
func postalAddressFromAddressDictionary(addressdictionary: Dictionary<NSObject,AnyObject>) -> CNMutablePostalAddress {

    let address = CNMutablePostalAddress()

    address.street = addressdictionary["Street"] as? String ?? ""
    address.state = addressdictionary["State"] as? String ?? ""
    address.city = addressdictionary["City"] as? String ?? ""
    address.country = addressdictionary["Country"] as? String ?? ""
    address.postalCode = addressdictionary["ZIP"] as? String ?? ""

    return address
}

// Create a localized address string from an Address Dictionary
func localizedStringForAddressDictionary(addressDictionary: Dictionary<NSObject,AnyObject>) -> String {

    return CNPostalAddressFormatter.stringFromPostalAddress(postalAddressFromAddressDictionary(addressDictionary), style: .MailingAddress)
}

答案 3 :(得分:13)

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    // get the address
    if let location = locations.last {
        CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (result: [CLPlacemark]?, err: NSError?) -> Void in
            if let placemark = result?.last
                , addrList = placemark.addressDictionary?["FormattedAddressLines"] as? [String]
            {
                let address =  addrList.joinWithSeparator(", ")
                print(address)
            }
        })
    }
}

以上是快速版本。

答案 4 :(得分:4)

我正在使用Swift 3 / XCode 8

ZYiOS's answer很好而且简短,但没有为我编译。

问题是如何从现有的地址字典到字符串地址。这就是我所做的:

import CoreLocation

func getAddressString(placemark: CLPlacemark) -> String? {
    var originAddress : String?

    if let addrList = placemark.addressDictionary?["FormattedAddressLines"] as? [String]
    {
        originAddress =  addrList.joined(separator: ", ")
    }

    return originAddress
}

答案 5 :(得分:2)

Swift 3 / Xcode 8 帮助Mehtod从CLPlaceMark获取地址

class func formattedAddress(fromPlacemark placemark: CLPlacemark) -> String{
    var address = ""

    if let name = placemark.addressDictionary?["Name"] as? String {
        address = constructAddressString(address, newString: name)
    }

    if let city = placemark.addressDictionary?["City"] as? String {
        address = constructAddressString(address, newString: city)
    }

    if let state = placemark.addressDictionary?["State"] as? String {
        address = constructAddressString(address, newString: state)
    }

    if let country = placemark.country{
      address = constructAddressString(address, newString: country)
    }

    return address
  }

答案 6 :(得分:1)

现在这很简单

UIPasteboard

答案 7 :(得分:0)

只需为CLLocation创建扩展程序:

typealias AddressDictionaryHandler = ([String: Any]?) -> Void

extension CLLocation {

    func addressDictionary(completion: @escaping AddressDictionaryHandler) {

        CLGeocoder().reverseGeocodeLocation(self) { placemarks, _ in
            completion(placemarks?.first?.addressDictionary as? [String: AnyObject])
        }
    }
}

示例:

let location = CLLocation()

location.addressDictionary { dictionary in

    let city = dictionary?["City"] as? String
    let street = dictionary?["Street"] as? String
}

答案 8 :(得分:0)

Swift 5版本

onLeave

答案 9 :(得分:0)

iOS 11+

import CoreLocation
import Contacts

public extension CLPlacemark {
    func formattedAddress() -> String? {
        guard let postalAddress = postalAddress else { return nil }
        let formatter = CNPostalAddressFormatter()
        formatter.style = .mailingAddress
        let formatterString = formatter.string(from: postalAddress)
        return formatterString.replacingOccurrences(of: "\n", with: " ")
    }
}