Search code examples
iosimessageimessage-extension

Can we launch a "link" in iMessage app?


I've got an iMessage app where basically I want to display a button and when pressed, launch another app like Safari or Maps etc.

I've tried:

if UIApplication.shared.canOpenURL(url){

but "UIApplication.shared" is only available in the main iOS app. Mine is an iMessage only app.

Any suggestions?


Solution

  • You can use the extensionContext property inside your MSMessagesAppViewController subclass to open URL like so:

    NSURL *url = [NSURL URLWithString:@"https://www.apple.com/"];
    [self.extensionContext openURL:url completionHandler:nil];
    

    I haven't tested this, but I use this method to launch my iOS application from my iMessage extension app using custom url scheme. I've also used this to launch the AppStore from my iMessage extension.

    Update:

    Since you said you just want to open Maps, you could try this:

    #import <MapKit/MapKit.h>
    
    - (void)openMaps {
        CLLocationCoordinate2D coordinates = CLLocationCoordinate2DMake(33.651092f, -117.744250f); // coordinates of your desired location
        MKCoordinateRegion regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, 5000, 5000); // 5000 is the distance in meters
        NSDictionary *options = @{MKLaunchOptionsMapCenterKey: [NSValue valueWithMKCoordinate:regionSpan.center],
                                  MKLaunchOptionsMapSpanKey: [NSValue valueWithMKCoordinateSpan:regionSpan.span]};
        MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:coordinates addressDictionary:nil];
        MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
        [mapItem setName:@"Irvine Spectrum Center"];
        [mapItem openInMapsWithLaunchOptions:options];
    }
    

    Let me know if that works out for you.