1. 程式人生 > >[iOS] Sharing text as a string to another app

[iOS] Sharing text as a string to another app

You could use a custom URL scheme. Apps like Facebook and WhatsApp generally have their own schemes that you can use to send data into those apps. See WhatsApp’s info here: Link

Alternatively, you could use a UIActivityViewController. This also supports other data types, not just strings (see this SO question

).

    
NSString *textToShare = @"要分享的文字內容"; 
NSArray *activityItems = @[textToShare];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
[self presentViewController:activityVC animated:YES completion:nil];

Here’s a nice blog post on this method:

Link

範例2號:

NSString *textToShare = @"要分享的文字內容"; 
UIImage *imageToShare = [UIImage imageNamed:@"iosshare.jpg"]; 
NSURL *urlToShare = [NSURL URLWithString:@"http://blog.csdn.net/hitwhylz"]; 
NSArray *activityItems = @[textToShare, imageToShare, urlToShare]; 


@property(nonatomic,copy) UIActivityViewControllerCompletionHandler completionHandler; // set to nil after call

typedef void (^UIActivityViewControllerCompletionHandler)(NSString *activityType, BOOL completed);

UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil]; 

//給activityVC的屬性completionHandler寫一個block。 
//用以UIActivityViewController執行結束後,被呼叫,做一些後續處理。 
UIActivityViewControllerCompletionHandler myBlock = ^(NSString *activityType,BOOL completed) 
{ 
 NSLog(@"activityType :%@", activityType); 
 if (completed) 
 { 
 NSLog(@"completed"); 
 } 
 else 
 { 
 NSLog(@"cancel"); 
 } 
 
 //放回上一級介面 
 [self.navigationController dismissModalViewControllerAnimated:YES]; 
 
}; 
 
// 初始化completionHandler,當post結束之後(無論是done還是cancell)該blog都會被呼叫 
activityVC.completionHandler = myBlock;