1. 程式人生 > >[iOS] ) should have a non-nil sourceView or barButtonItem set before the presentation occurs

[iOS] ) should have a non-nil sourceView or barButtonItem set before the presentation occurs

You aren’t initialising the activityViewController on iPad so it will always be nil.

Try:

- (void)shareLeaflet
{
    NSString *forwardedString = [[NSString alloc] initWithFormat:@"Check out this leaflet\n\n %@ \n\nself.theURLToShare];
    UIActivityViewController *activityViewController = [[UIActivityViewController
alloc] initWithActivityItems:[NSArray arrayWithObjects:forwardedString, nil] applicationActivities:nil]; if (IDIOM == IPAD) { NSLog(@"iPad"); activityViewController.popoverPresentationController.sourceView = self.view; // activityViewController.popoverPresentationController.sourceRect = self.frame;
[self presentViewController:activityViewController animated:YES completion:nil]; } else { NSLog(@"iPhone"); [self presentViewController:activityViewController animated:YES completion
:nil]; }

And then to display it like in the image: (_shareBarButton is the UIBarButtonItem that you want the popover to display from)

- (void)shareLeaflet
    {
        NSString *forwardedString = [[NSString alloc] initWithFormat:@"Check out this leaflet\n\n %@ \n\nself.theURLToShare];
        UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:[NSArray arrayWithObjects:forwardedString, nil] applicationActivities:nil];

        if (IDIOM == IPAD)
        {
            NSLog(@"iPad");
            activityViewController.popoverPresentationController.sourceView = self.view;
    //        activityViewController.popoverPresentationController.sourceRect = self.frame;

           _popover = [[UIPopoverController alloc] initWithContentViewController:activityViewController];
           _popover.delegate = self;
           [_popover presentPopoverFromBarButtonItem:_shareBarButton permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        }
        else
        {
            NSLog(@"iPhone");
            [self presentViewController:activityViewController 
                              animated:YES 
                            completion:nil];
        }