SMS behavior using UIActivityViewController - ios

I'm using a UIActivityViewController to share some text from within my app. I've subclassed the UIActivityItemProvider so that I can handle the text depending on the sharing application selected. Before I present the view controller, I create a text file that can get attached to a mail message. (I write the file to a URL and add it to the shared items array.) If the user taps the Mail icon, the text document file gets attached to the message and all is good in the world. Here is the code I use:
- (IBAction)shareBarButtonPressed:(UIBarButtonItem *)sender
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *resultsFile = [docPath stringByAppendingString:#"/results.txt"];
[self createResultFile];
NSURL *fileUrl = [NSURL fileURLWithPath:resultsFile];
NSData *fileData = [[NSData alloc]initWithContentsOfFile:resultsFile];
[fileData writeToURL:fileUrl atomically:YES];
NSString *testString = #"This is my string";
PRActivityProvider *activityProvider = [[PRActivityProvider alloc] initWithPlaceholderItem:[self fillResultFromView]];
NSArray *items = #[activityProvider, testString];
UIActivityViewController *activityViewController =
[[UIActivityViewController alloc] initWithActivityItems:items
applicationActivities:nil];
NSString *subject = [NSString stringWithFormat:#"Results: %#",self.result.eventName];
[activityViewController setValue:subject forKey:#"subject"];
[activityViewController setExcludedActivityTypes:
#[UIActivityTypeSaveToCameraRoll,
UIActivityTypeAssignToContact,
UIActivityTypePostToTencentWeibo,
UIActivityTypeCopyToPasteboard]];
[self presentViewController:activityViewController animated:YES completion:nil];
[activityViewController setCompletionHandler:^(NSString *act, BOOL done)
{
NSString *ServiceMsg = nil;
if ( [act isEqualToString:UIActivityTypeMail] ) ServiceMsg = #"Results sent!";
if ( [act isEqualToString:UIActivityTypePostToTwitter] ) ServiceMsg = #"Results posted on Twitter!";
if ( [act isEqualToString:UIActivityTypePostToFacebook] ) ServiceMsg = #"Results posted on FaceBook!";
if ( [act isEqualToString:UIActivityTypeMessage] ) ServiceMsg = #"SMS sent!";
if ( done )
{
UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:ServiceMsg message:#"" delegate:nil cancelButtonTitle:#"ok" otherButtonTitles:nil];
[Alert show];
}
}];
However, I have two problems:
First, when the user taps the SMS icon to send the NSString in a text, the file that got created earlier also gets attached (or imbedded) in the text of the message. Is there a way to 'selectively' attach a file depending on which sharing service is selected? Or maybe a way to remove the file when the user taps the SMS icon? Is there some housekeeping that I need to do in the activity provider subclass to clean up the text message?
Second, on a real device the SMS message doesn't get to its target. The completion handler triggers and shows the SMS message completes, but I never receive it. Not sure there is a race condition here or not - it actually worked once where I received the text message with the string.
Here is the activityController code:
- (id) activityViewController:(UIActivityViewController *)activityViewController
itemForActivityType:(NSString *)activityType
// the number of item to share
static UIActivityViewController *shareController;
static int itemNo;
if (shareController == activityViewController && itemNo < numberOfSharedItems - 1)
itemNo++;
else {
itemNo = 0;
shareController = activityViewController;
}
PRResults *result = [[PRResults alloc]init];
result = self.placeholderItem;
// twitter
if ([activityType isEqualToString: UIActivityTypePostToTwitter]) {
return [self makeTweetFromResult:result];
}
// SMS text message
else if ([activityType isEqualToString: UIActivityTypeMessage]) {
return [self makeTweetFromResult:result];
}
// email
else if ([activityType isEqualToString: UIActivityTypeMail]) {
return #"Open the attached results file in a notepad app to view.";
}
// Facebook
else if ([activityType isEqualToString:UIActivityTypePostToFacebook]) {
return [self makeFacebookPostFromResult:result];
}
return nil;

Related

UIActivityViewController not passing new line characters to some activities

I am using the following code to set up UIActivityViewController:
NSArray *activityItems = [NSArray arrayWithObjects:[self textMessageToShare], nil];
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
[activityViewController setCompletionHandler:^(NSString *activityType, BOOL completed) {
if (completed) {
[self sendFeedbackWithIndexPath:indexPath AndLikeType:100 AndCell:nil];
}
}];
[self.navigationController presentViewController:activityViewController
animated:YES
completion:^{
// ...
}];
Issue is that when I copy a message or post to facebook or twitter or email or gmail app or to default Messages app, the new line characters that are in [self textMessageToShare] are maintained. However, if I share to other activities like WhatsApp or Viber - all the new line characters are removed, and the whole message is sent as one single line.
Whereas, if I share just text through iOS default Notes app, new line characters are maintained when shared to these apps. How would the Notes app be storing the new line characters? I am using \n as the new line character.
For my life unable to even find the reason. Can anyone help?
I was able to make it work by converting the newline characters to "<br/>":
_myDataString= self.textview.text;
_myDataString= [_myDataString stringByReplacingOccurrencesOfString:#"\n" withString:#"<br/>"];
Please check the new line issue in whats app share using uiactivityviewcontroller.
#import <UIKit/UIKit.h>
#interface ShareActivity : UIActivityItemProvider
#property (nonatomic, strong) NSString *message;
#property (nonatomic, strong) NSArray *activities;
#end
#import "ShareActivity.h"
#implementation ShareActivity
#synthesize message = _message;
#synthesize activities = _activities;
- (id) activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType
{
if([activityType isEqualToString:#"net.whatsapp.WhatsApp.ShareExtension"])
{
return [self.message stringByReplacingOccurrencesOfString:#"\n" withString:#"<br/>"];
}
else if ([self.activities containsObject:activityType])
{
return [self.message stringByReplacingOccurrencesOfString:#"\n" withString:#"<br/>"];
}
else
{
return self.message;
}
return nil;
}
- (id) activityViewControllerPlaceholderItem:(UIActivityViewController *)activityViewController
{
return #"";
}
In View Controller Class on any action button to pop up the share view
Apply this action on any button action
-(void)shareAction
{
ShareActivity *shareObj = [[ShareActivity alloc] initWithPlaceholderItem:#""];
NSString *message = #"New\nLine\nText\nMessage";
[shareObj setMessage:message];
NSArray* dataToShare = #[shareObj];
NSArray *excludeActivities = #[UIActivityTypePrint,UIActivityTypeOpenInIBooks,UIActivityTypeAddToReadingList,UIActivityTypePostToTencentWeibo,UIActivityTypeSaveToCameraRoll,UIActivityTypeAirDrop];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
activityVC.excludedActivityTypes = excludeActivities;
[activityVC setCompletionHandler:^(NSString *act, BOOL done)
{
NSString *ServiceMsg = nil;
if ( [act isEqualToString:UIActivityTypeMail] )
{
ServiceMsg = #"Mail sent!";
}
else if ( [act isEqualToString:UIActivityTypePostToTwitter] )
{
ServiceMsg = #"Post on twitter, ok!";
}
else if ( [act isEqualToString:UIActivityTypePostToFacebook] )
{
ServiceMsg = #"Post on facebook, ok!";
}
else if ( [act isEqualToString:UIActivityTypeCopyToPasteboard] )
{
ServiceMsg = #"Message copy to pasteboard";
}
else if ( [act isEqualToString:UIActivityTypePostToFlickr] )
{
ServiceMsg = #"Message sent to flickr";
}
else if ( [act isEqualToString:UIActivityTypePostToVimeo] )
{
ServiceMsg = #"Message sent to Vimeo";
}
else
{
}
}];
[self presentViewController:activityVC animated:YES completion:nil];
}
hi its me again i was looking for the right answer
and i found that you can do it by using a Custom Share Message to Different Providers .
and you can find an example from this Code check for MyActivityItemProvider class .
https://github.com/apascual/flip-your-phone
i hove a problem posting the code here so i think the link above will help
Thanks to MuslimDev2015 I have been able to develop a solution:
https://github.com/lorenzoPrimi/NewlineActivityItemProvider
Try it and let me know.
You can send the text as multiple items each item is just one line.
let lines = text.components(separatedBy: "\n")
let activityViewController = UIActivityViewController(activityItems: lines, applicationActivities: nil)

UIActivityViewController issue iOS 7 and iOS 8?

I’m building an article reading app for iPad. I have integrated a social sharing functionality which means user can share articles on Facebook, and google mail.
I’m using UIActivityViewController for sharing.
There is a bar button item,when user click on that UIActivityViewController opens.I updated Xcode 6
When I run on simulator it runs fine But I run on real device(iPad) with iOS 7,the app get crash on clicking on bar button item.
this is my code:
- (IBAction)ysshareAction:(id)sender
{
NSURL *linkURL = [NSURL URLWithString:_DetailModal1[4]];//article url
NSMutableAttributedString *stringText = [[NSMutableAttributedString alloc] initWithString:_DetailModal1[0]];//_DetailModal1[0] contain article title////
[stringText addAttribute:NSLinkAttributeName value:linkURL range:NSMakeRange(0, stringText.length)];
NSArray * itemsArray = #[[NSString stringWithFormat:#"%#",_DetailModal1[0]], [NSURL URLWithString:_DetailModal1[4]]];
NSArray * applicationActivities = nil;
UIActivityViewController * AVC = [[UIActivityViewController alloc] initWithActivityItems:itemsArray applicationActivities:applicationActivities];
AVC.popoverPresentationController.sourceView = _webView;
[self presentViewController:AVC animated:YES completion:nil];
[AVC setCompletionHandler:^(NSString *act, BOOL done)
{
if([act isEqualToString:UIActivityTypeMail]) {
ServiceMsg = #"Mail sent!";
} else if([act isEqualToString:UIActivityTypePostToTwitter]) {
ServiceMsg = #"Article Shared!";
} else if([act isEqualToString:UIActivityTypePostToFacebook]) {
ServiceMsg = #"Article Shared!";
} else if([act isEqualToString:UIActivityTypeMessage]) {
ServiceMsg = #"SMS sent!";
} else if([act isEqualToString:UIActivityTypeAddToReadingList]) {
ServiceMsg = #"Added to Reading List";
} else if([act isEqualToString:UIActivityTypeCopyToPasteboard]){
ServiceMsg = #"Copied Link";
}
if ( done )
{
UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:ServiceMsg message:#"" delegate:nil cancelButtonTitle:#"ok" otherButtonTitles:nil];
[Alert show];
}
}];
}
Help is appreciated!
Following line is the issue
AVC.popoverPresentationController.sourceView = _webView;
You will have to put iOS8 condition in order popoverPresentationController is introduced for iOS 8 and later so you can not use it with iOS 7
For checking for iOS8 you can define a macro like found from here
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
And use it in following way.
NSURL *linkURL = [NSURL URLWithString:_DetailModal1[4]];//article url
NSMutableAttributedString *stringText = [[NSMutableAttributedString alloc] initWithString:_DetailModal1[0]];//_DetailModal1[0] contain article title////
[stringText addAttribute:NSLinkAttributeName value:linkURL range:NSMakeRange(0, stringText.length)];
NSArray * itemsArray = #[[NSString stringWithFormat:#"%#",_DetailModal1[0]], [NSURL URLWithString:_DetailModal1[4]]];
NSArray * applicationActivities = nil;
UIActivityViewController * AVC = [[UIActivityViewController alloc] initWithActivityItems:itemsArray applicationActivities:applicationActivities];
if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"8.0")){
AVC.popoverPresentationController.sourceView = _webView;
}
[self presentViewController:AVC animated:YES completion:nil];
Refer this for more info about what has changed for UIActivityViewController in iOS8
A lot might argue that checking for existence of the class explicitly is better than checking a hard coded version number. UIPopoverPresentationController may be deprecated at some future point, or there might be a (future ?) device which does not support the class, like the iPhone never used to support UIPopoverController or UISplitViewController..
if ( NSClassFromString(#"UIPopoverPresentationController") ) {
AVC.popoverPresentationController.sourceView = _webView;
}
In Swift, You can use '?' instead checking OS version.
AVC.popoverPresentationController?.sourceView = _webView

Cancel button action in zbar shows blank view

I am using tab bar in my iOS app. When I tap on the scan tab, i invoked the delegate method to start the camera immediately on scan tab. When I start the camera to scan the QR Code and tap on cancel button before scanning, I get the blank view. How to display the view when camera is dismissed
- (void) openCameraScanner
{
ZBarReaderViewController *reader = [[ZBarReaderViewController alloc] init];
reader.readerDelegate = self;
reader.supportedOrientationsMask = ZBarOrientationMaskAll;
reader.showsZBarControls = YES;
ZBarImageScanner *scanner = reader.scanner;
[scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 0];
[self presentViewController:reader animated:YES completion:nil];
reader.showsZBarControls = YES;
//reader.cameraOverlayView = [self commonOverlay];
}
- (void) imagePickerController: (UIImagePickerController*) reader
didFinishPickingMediaWithInfo: (NSDictionary*) info
{
// ADD: get the decode results
id<NSFastEnumeration> results =
[info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for(symbol in results)
// EXAMPLE: just grab the first barcode
break;
// EXAMPLE: do something useful with the barcode data
//resultsView.text = symbol.data;
NSString *urlString = symbol.data;
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"Query after scan = %#", [url query]);
//Extract id from URL which is there in QR Code --- start
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
for(NSString *param in [urlString componentsSeparatedByString:#"&"])
{
NSArray *elements = [param componentsSeparatedByString:#"="];
if([elements count]<2)
continue;
[dictionary setObject:[elements objectAtIndex:1] forKey:[elements objectAtIndex:0]];
NSLog(#"value is == %#", [elements objectAtIndex:1]);
//Extract id from URL which is there in QR Code --- end
if([[elements objectAtIndex:1] intValue])
{
NSUserDefaults *defaultsForAsk = [NSUserDefaults standardUserDefaults];
idToAsk = [NSString stringWithFormat:#"%d",[[elements objectAtIndex:1] intValue]];
[defaultsForAsk setObject:idToAsk forKey:#"IDTOASKVIEW"];
flagToShowView = YES;
listViewCntrl.getFlag = flagToShowView;
[self viewDidLoadForDynamicFields];
}
else if([elements objectAtIndex:1] == [NSNull null])
{
[reader dismissViewControllerAnimated:YES completion:Nil];
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Invalid QR Code scanned" message:#"Please scan Collaborator's QR Code" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[message show];
}
}
image.image =
[info objectForKey: UIImagePickerControllerOriginalImage];
// ADD: dismiss the controller (NB dismiss from the *reader*!)
//[reader dismissViewControllerAnimated:YES completion:nil];
[reader dismissViewControllerAnimated:YES completion:Nil];
}
You can re display the view using -(void)viewWillAppear:(BOOL)animated method of your ViewController class.

MFMailComposeViewController only presented after second tap

I want to present a MFMailComposeViewController from a modal view controller. Basically this method works, but it does not work reliably:
-(void)sendMailTapped:(id)sender{
[self resetButtonsStateAfterTapping:sender];
[self dismissPopover];
if (filesize>10) {
[self showAlertForExceededMaximumAttachmentSize];
return;
}
#try {
MFMailComposeViewController *picker =
[[MFMailComposeViewController alloc] init];
if ([MFMailComposeViewController canSendMail]) {
picker.mailComposeDelegate = self;
NSURL *path =[NSURL urlWithPath:[pageInfoDict valueForKey:#"file_name"]
docId:[pageInfoDict valueForKey:#"id_doc"]
encrypted:[[pageInfoDict valueForKey:#"encrypted"]
boolValue]] ;
NSString *fileName = [pageInfoDict valueForKey:#"title"];
if([fileName length] == 0) {
fileName = [path lastPathComponent];
}
if(![fileName hasSuffix:[path pathExtension]]){
fileName=[fileName stringByAppendingFormat:#".%#",[path pathExtension]];
}
[picker setSubject:[#"Send document: " stringByAppendingString:fileName]];
NSArray *ccRecipients = [NSArray arrayWithObjects:
[[CustomisationConfig getAppConfig] getCCMail],nil];
[picker setCcRecipients:ccRecipients];
NSArray *bccRecipients = [NSArray arrayWithObjects:
[[CustomisationConfig getAppConfig] getBCCMail],nil];
[picker setBccRecipients:bccRecipients];
NSData *myData = [path decryptedData];
[picker addAttachmentData:myData
mimeType:fileMIMEType(fileName) fileName:fileName];
NSString *emailBody = [NSString stringWithFormat:
#"\n\nThis file was sent using %#.",
[DCConfiguration getHumanReadableAppName] ];
[picker setMessageBody:emailBody isHTML:NO];
[self presentViewController:picker animated:true completion:^(void){}];
}
}
#catch (NSException *exception) {
NSLog(#"ContextMenuViewController sendMailTapped:%#",exception.description);
}
}
If I restart my iPad and open the app, the picker will be presented only on the second tap on the corresponding button.
If I click again on the button after this, the picker will be presented on first touch everytime and it works perfectly, until I shutdown and restart the iPad.
The following is printed to the console:
Warning: Attempt to present <MFMailComposeViewController: 0x200cbb70> on <ContextMenuViewController: 0x200cd1a0> whose view is not in the window hierarchy!
What is calling the sendMailTapped: method? If its interface builder, you need to change it to IBAction instead of void, and connect them in interface builder.

iOS : How to retrieve sender in one IBAction from the multiple item in picker view selection?

I need one button called email button to do one selection from multiple item from picker view to attach that selected item via email. I am stuck at the IBAction. Here is my progress.
M File :
-(void)pickerViewEmail:(UIPickerView *)pickerViewEmail didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if ([[musicList objectAtIndex:row] isEqual:#"m1"])
{
MFMailComposeViewController *pickerEmail = [[MFMailComposeViewController alloc] init];
pickerEmail.mailComposeDelegate = self;
NSString *path = [[NSBundle mainBundle] pathForResource:#"m1" ofType:#"mp3"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[pickerEmail addAttachmentData:myData mimeType:#"audio/mp3" fileName:#"m1"];
[pickerEmail setSubject:#"Hello!"];
// Set up recipients
NSArray *toRecipients = [NSArray arrayWithObject:#"first#example.com"];
NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com", #"third#example.com", nil];
NSArray *bccRecipients = [NSArray arrayWithObject:#"fourth#example.com"];
[pickerEmail setToRecipients:toRecipients];
[pickerEmail setCcRecipients:ccRecipients];
[pickerEmail setBccRecipients:bccRecipients];
// Fill out the email body text
NSString *emailBody = #"Hello";
[pickerEmail setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:pickerEmail animated:YES];
[pickerEmail release];
}
if ([[musicList objectAtIndex:row] isEqual:#"m2"])
{
}
if ([[musicList objectAtIndex:row] isEqual:#"m3"])
{
}
IBAction :
-(IBAction)showEmail
{
if ([MFMailComposeViewController canSendMail])
{
[self pickerEmail]; I have a yellow error when i call this. What is the right solution?
}
else
{
}
}
iOS : How to attach a multiple attachment file in one button using pickerview method?
I don't understand your call [self pickerEmail]
Higher in your code, pickerEmail seems to be an object, of type MFMailComposeViewController, not a method. So the call [self pickerEmail] does not have any sense in Objective-C

Resources