Открыть карты с определенным адресом iOS 7

Я пытаюсь заставить свое приложение открыть приложение Apple Maps и получить адрес. Я пробовал это:

- (IBAction)openInMaps:(id)sender {
    NSString *addressString = @"http://maps.apple.com/?q=1 Infinite Loop, Cupertino, CA";
    NSURL *url = [NSURL URLWithString:addressString];
    [[UIApplication sharedApplication] openURL:url];
}

и это :

- (IBAction)openInMaps:(id)sender {
    NSString *addressString = @"http://maps.apple.com/?q=1_Infinite_Loop,_Cupertino,_CA";
    NSURL *url = [NSURL URLWithString:addressString];
    [[UIApplication sharedApplication] openURL:url];
}

Но кнопка просто действует так, как будто она ни к чему не привязана. Но это работает:

- (IBAction)openInMaps:(id)sender {
    NSString *addressString = @"http://maps.apple.com/?q=Cupertino,CA";
    NSURL *url = [NSURL URLWithString:addressString];
    [[UIApplication sharedApplication] openURL:url];
}

Итак, всякий раз, когда это пространство, оно не работает. Как я могу открыть этот адрес?


person JCode    schedule 13.02.2014    source источник
comment
ознакомьтесь с документацией developer.apple.com/library/ios /избранные статьи/   -  person Josh Lowe    schedule 13.02.2014
comment
Спасибо, чувак, даже не знал, что там есть... посмотрю   -  person JCode    schedule 13.02.2014
comment
Я делаю это: NSString *addressString = [NSString stringWithFormat:@maps.apple.com/?q=1+Infinite+Loop,+Cupertino,+CA];   -  person JCode    schedule 13.02.2014
comment
Не используйте без необходимости stringWithFormat:. Просто назначьте строку напрямую.   -  person rmaddy    schedule 13.02.2014


Ответы (4)


Вам нужно правильно экранировать пробелы в URL:

NSString *addressString = @"http://maps.apple.com/?q=1%20Infinite%20Loop,%20Cupertino,%20CA";

Изменить - кажется, использование + вместо %20 для пробелов решает проблему.

Итак, чтобы заставить его работать правильно, вы должны использовать это:

NSString *addressString = @"http://maps.apple.com/?q=1+Infinite+Loop,+Cupertino,+CA";
person rmaddy    schedule 13.02.2014
comment
Все еще ведет себя так, как будто кнопка ничего не делает. Однако я получаю сообщение об ошибке: Недопустимый спецификатор преобразования «I». Я знаю, что это значит, но как исправить? - person JCode; 13.02.2014

Версия Swift 2, которая хорошо отформатирована, безопасно обрабатывает дополнительные параметры и не приведет к сбою вашего приложения:

let baseUrl: String = "http://maps.apple.com/?q="
let encodedName = "address".stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet()) ?? ""
let finalUrl = baseUrl + encodedName
if let url = NSURL(string: finalUrl) {
    UIApplication.sharedApplication().openURL(url)
}
person Chris C    schedule 25.04.2016

Вот как я это делаю в Objective C... Я всегда сначала пробую карту Waze, потому что, честно говоря, это потрясающий соус, я добавил права доступа к файлу PLIST в конце:

- (IBAction)getDirectionsAction:(id)sender {
    NSURL *googleURL = [[NSURL alloc]
        initWithString:[NSString stringWithFormat:@"comgooglemaps://?daddr=%@", @"44.294349,-70.326973"]];

    NSURL *googleWebURL =
        [[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://www.maps.google.com/maps?daddr=%@",
                                                                 @"44.294349,-70.326973"]];

    NSURL *appleURL = [NSURL URLWithString:@"http://maps.apple.com/?daddr=311+East+Buckfield+Road+Buckfield+Maine"];

    NSURL *wazeURL = [NSURL URLWithString:@"waze://?ll=44.294349,-70.326973&navigate=yes"];

    // Lets try the Waze app first, cuz we like that one the most
    if ([[UIApplication sharedApplication] canOpenURL:wazeURL]) {
        [[UIApplication sharedApplication] openURL:wazeURL
                                           options:@{}
                                 completionHandler:^(BOOL success){
                                 }];
        return;
    }

    // Lets try the Apple Maps app second (great success rate)
    if ([[UIApplication sharedApplication] canOpenURL:appleURL]) {
        [[UIApplication sharedApplication] openURL:appleURL
                                           options:@{}
                                 completionHandler:^(BOOL success){
                                 }];
        return;
    }
    // If those 2 are unsuccessful, let's try the Google Maps app
    if ([[UIApplication sharedApplication] canOpenURL:googleURL]) {
        [[UIApplication sharedApplication] openURL:googleURL
                                           options:@{}
                                 completionHandler:^(BOOL success){
                                 }];
        return;
    }
    // Uh, oh...Well, then lets launch it from the web then.
    else {
        [[UIApplication sharedApplication] openURL:googleWebURL
                                           options:@{}
                                 completionHandler:^(BOOL success){

                                 }];
    }
}

ДЛЯ ФАЙЛА PLIST

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>http://maps.apple.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
        <key>http://maps.google.com/</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <true/>
        </dict>
    </dict>
</dict>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>waze</string>
    <string>comgooglemaps</string>
</array>
<key>NSLocationAlwaysUsageDescription</key>
<string>For Use for directions</string>

1x

2x

3x

person Community    schedule 11.03.2017

Свифт 3 версия:

let baseUrl: String = "http://maps.apple.com/?q="
let encodedName = "yourAddress".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let finalUrl = baseUrl + encodedName
if let url = URL(string: finalUrl)
    {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
person Siegfoult    schedule 09.05.2017