There is a "cancel" button that comes by default with UIActivityViewController. How can I call a method when that button is pressed?
I have written this code to share the audio file.
NSURL* outURL;
UIActivityViewController *controller;
if (&UIActivityTypeAirDrop != NULL) {
controller.excludedActivityTypes = #[UIActivityTypeAirDrop];
for (int i=0;i<[arrayselecturls count];i++) {
str_SongsselectName=[[arrayselecturls objectAtIndex:i] objectForKey:#"Song"];
NSString* ext = [TSLibraryImport extensionForAssetURL:[[arrayselecturls objectAtIndex:i] objectForKey:#"SongURl"]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
outURL = [[NSURL fileURLWithPath:[documentsDirectory stringByAppendingPathComponent:[[arrayselecturls objectAtIndex:i] objectForKey:#"Song"]]] URLByAppendingPathExtension:ext];
NSString *str_selectfilename=[NSString stringWithFormat:#"%#.mp3",str_SongsselectName];
// NSURL *url = outURL;
// NSLog(#"url is %#",url);
NSArray *objectsToShare = [NSArray arrayWithObjects:outURL,str_selectfilename, nil];
// objectsToShare = #[outURL];
controller = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
// Exclude all activities except AirDrop.
NSArray *excludedActivities = #[UIActivityTypePostToTwitter, UIActivityTypePostToFacebook,
UIActivityTypePostToWeibo,
UIActivityTypeMessage, UIActivityTypeMail,
UIActivityTypePrint, UIActivityTypeCopyToPasteboard,
UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll,
UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr,
UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo];
controller.excludedActivityTypes = excludedActivities;
}
[self presentViewController:controller animated:YES completion:nil];
}
else{
UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"Your device has no Airdrop!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[Alert show];
}
oooooop!
I got the solution.This solution is working fine for me.
-(IBAction)ActionArtsist_airdropClick:(id)sender{
view_shareView.hidden=YES;
borderImageView . hidden =YES;
darkBg . hidden =YES;
view_artistdarlView.hidden=YES;
tblv_albumSongTableView.userInteractionEnabled=YES;
Data = [NSData dataWithContentsOfURL: exportURL];
UIActivityViewController *controller;
if (&UIActivityTypeAirDrop != NULL) {
controller.excludedActivityTypes = #[UIActivityTypeAirDrop];
NSString *str_selectfilename;
for (int i=0;i<[arr_atistsongsSelct count];i++) {
str_songsSlelectName=[[arr_atistsongsSelct objectAtIndex:i] objectForKey:#"songsName"];
NSString* ext = [TSLibraryImport extensionForAssetURL:[[arr_atistsongsSelct objectAtIndex:i] objectForKey:#"songsURl"]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL* outURL = [[NSURL fileURLWithPath:[documentsDirectory stringByAppendingPathComponent:[[arr_atistsongsSelct objectAtIndex:i] objectForKey:#"songsName"]]] URLByAppendingPathExtension:ext];
str_selectfilename=[NSString stringWithFormat:#"%#.mp3",str_songsSlelectName];
NSArray *objectsToShare = [NSArray arrayWithObjects:outURL,str_selectfilename, nil];
controller = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
// Exclude all activities except AirDrop.
NSArray *excludedActivities = #[UIActivityTypePostToTwitter, UIActivityTypePostToFacebook,
UIActivityTypePostToWeibo,
UIActivityTypeMessage, UIActivityTypeMail,
UIActivityTypePrint, UIActivityTypeCopyToPasteboard,
UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll,
UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr,
UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo];
controller.excludedActivityTypes = excludedActivities;
}
This is the handling function.
**[controller setCompletionHandler:^(NSString *activityType, BOOL completed) {
if (!completed)
{
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
[self performSelector:#selector(ActiviHideArtistSong) withObject:self afterDelay:4.0 ];
}
return;
}];**
upto here
[self presentViewController:controller animated:YES completion:nil];
}
else{
UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"Your device has no Airdrop!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[warningAlert show];
}
}
-(void)ActiviHideArtistSong{
[self btnimageArtistSongscheck_lick:nil];
}
Related
I need to zip my log file and email it. I'm using Objective-zip for zipping my file. And this is my code
-(void)mailLogFile {
if ([MFMailComposeViewController canSendMail]) {
NSDictionary *user = [[DBHelper getSharedInstance] getCurrentUser];
NSString *propertyQuery = [NSString stringWithFormat:#"SELECT RecentActivityId,PropertyPIC,PropertyId,Message,IsSynced,ActivityTime,ErrorCode,ErrorMessage,ErrorData,EntityId,TableNames From RecentActivity ORDER BY ActivityTime desc"];
NSArray *resultArry = [[DBHelper getSharedInstance] getRecordsBySQL:propertyQuery];
NSLog(#"This is the eNVDS in Recent Activity:%#" ,resultArry);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity:%#" ,resultArry]];
NSPredicate *notsynced = [NSPredicate predicateWithFormat:#"IsSynced == 0 || IsSynced == %#",#"0"];
NSArray *notsyncedenvds = [resultArry filteredArrayUsingPredicate:notsynced];
NSLog(#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds]];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *WritableDBPath= [documentsDirectory stringByAppendingPathComponent:#"Logfile.txt"];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"test.zip"];
NSData *zipdata = [NSData dataWithContentsOfFile:path];
NSData *data = [NSData dataWithContentsOfFile:WritableDBPath];
//OZZipFile *readFile = [[OZZipFile alloc] initWithFileName:path mode:OZZipFileModeCreate];
OZZipFile *zipFile32= [[OZZipFile alloc] initWithFileName:path mode:OZZipFileModeCreate];
OZZipWriteStream *stream= [zipFile32 writeFileInZipWithName:#"Logfile.txt" compressionLevel:OZZipCompressionLevelBest];
[stream writeData:data];
[stream finishedWriting];
NSString *emailTitle = [NSString stringWithFormat:#"Log file of %#",[NSDate date]];
NSMutableString *messageBody = [NSMutableString stringWithFormat:#"Login with %#",user[#"Username"]];
if(![user[#"PropertyName"] isKindOfClass:[NSNull class]])[messageBody appendFormat:#"\n%#",user[#"PropertyName"]];
[messageBody appendFormat:#"\nApp version : %#",APP_VERSION];
[messageBody appendFormat:#"\nPlease describe your problem scenario here."];
[messageBody appendFormat:#"\n\n\nThanks"];
NSArray *toRecipents = [NSArray arrayWithObject:#"support#aglive.com"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipents];
[mc addAttachmentData:zipdata mimeType:#"application/zip" fileName:#"test.zip"];
[self presentViewController:mc animated:YES completion:nil];
[zipFile32 close];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Aglive Pro" message:#"You have not configured your mail account. Please configure your mail account from the device settings." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
}
right now I'm able to send a zip file in email but when I do unzip and open the file in my mobile or mac I get alert saying that The document “Logfile 4.txt” could not be opened. The file isn’t in the correct format. I don't know where I'm going wrong.
This code worked for me
-(void)mailLogFile {
if ([MFMailComposeViewController canSendMail]) {
NSDictionary *user = [[DBHelper getSharedInstance] getCurrentUser];
NSString *propertyQuery = [NSString stringWithFormat:#"SELECT RecentActivityId,PropertyPIC,PropertyId,Message,IsSynced,ActivityTime,ErrorCode,ErrorMessage,ErrorData,EntityId,TableNames From RecentActivity ORDER BY ActivityTime desc"];
NSArray *resultArry = [[DBHelper getSharedInstance] getRecordsBySQL:propertyQuery];
NSLog(#"This is the eNVDS in Recent Activity:%#" ,resultArry);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity:%#" ,resultArry]];
NSPredicate *notsynced = [NSPredicate predicateWithFormat:#"IsSynced == 0 || IsSynced == %#",#"0"];
NSArray *notsyncedenvds = [resultArry filteredArrayUsingPredicate:notsynced];
NSLog(#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds]];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *WritableDBPath= [documentsDirectory stringByAppendingPathComponent:#"Logfile.txt"];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Logfile.zip"];
NSData *zipdata = [NSData dataWithContentsOfFile:path];
NSData *data = [NSData dataWithContentsOfFile:WritableDBPath];
OZZipFile *zipFile32= [[OZZipFile alloc] initWithFileName:path mode:OZZipFileModeCreate];
//NSData *zipdata2 = [NSData dataWithContentsOfFile:zipFile32];
OZZipWriteStream *stream= [zipFile32 writeFileInZipWithName:#"LogFile.txt" compressionLevel:OZZipCompressionLevelBest];
[stream writeData:data];
[stream finishedWriting];
[zipFile32 close];
NSString *emailTitle = [NSString stringWithFormat:#"Log file of %#",[NSDate date]];
NSMutableString *messageBody = [NSMutableString stringWithFormat:#"Login with %#",user[#"Username"]];
if(![user[#"PropertyName"] isKindOfClass:[NSNull class]])[messageBody appendFormat:#"\n%#",user[#"PropertyName"]];
[messageBody appendFormat:#"\nApp version : %#",APP_VERSION];
[messageBody appendFormat:#"\nPlease describe your problem scenario here."];
[messageBody appendFormat:#"\n\n\nThanks"];
NSArray *toRecipents = [NSArray arrayWithObject:#"support#aglive.com"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipents];
//
if(zipdata== 0 && zipdata==nil)
{
[self mailLogFile];
}
else
{
[mc addAttachmentData:zipdata mimeType:#"application/zip" fileName:#"Logfile.zip"];
[self presentViewController:mc animated:YES completion:nil];
}
In my project I need to create and send a vCard (vcf file) that must include an image too. I did everything right except I can not add image to the vCard. I have shared my code below.
- (IBAction)shareButtonPressed:(UIButton *)sender {
NSError *error;
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:#"vCard.vcf"];
[[self vCardRepresentation] writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:#[#"Test", [NSURL fileURLWithPath:filePath]] applicationActivities:nil];
activityVC.excludedActivityTypes = #[UIActivityTypePostToWeibo, UIActivityTypeAssignToContact, UIActivityTypeMessage, UIActivityTypeCopyToPasteboard];
[self presentViewController:activityVC animated:YES completion:^{
}];
}
- (NSString *)vCardRepresentation
{
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:#"Rokon"], 1.0);
[mutableArray addObject:#"BEGIN:VCARD"];
[mutableArray addObject:#"VERSION:3.0"];
[mutableArray addObject:[NSString stringWithFormat:#"FN:%#", #"Rokon"]];
[mutableArray addObject:[NSString stringWithFormat:#"TEL:%#",#"+8801811536248"]];
[mutableArray addObject:[NSString stringWithFormat:#"PHOTO;BASE64:%#",[imageData base64EncodedDataWithOptions:0]]];
[mutableArray addObject:#"END:VCARD"];
return [mutableArray componentsJoinedByString:#"\n"];
}
- (void)shareContact{
[self emptySandbox];
NSString *contactName = [NSString stringWithFormat:#"%# %#",[Person sharedInstance].firstName, [Person sharedInstance].lastName];
NSError *error;
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.vcf", contactName]];
[[self vCardRepresentation] writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:#[contactName, [NSURL fileURLWithPath:filePath]] applicationActivities:nil];
activityVC.excludedActivityTypes = #[UIActivityTypePostToWeibo, UIActivityTypeAssignToContact, UIActivityTypeCopyToPasteboard];
[activityVC setValue:contactName forKey:#"subject"];
[self presentViewController:activityVC animated:YES completion:^{
}];
}
- (NSString *)vCardRepresentation
{
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
NSData *imageData = UIImageJPEGRepresentation([Person sharedInstance].profileImage, 1.0);
[mutableArray addObject:#"BEGIN:VCARD"];
[mutableArray addObject:#"VERSION:3.0"];
[mutableArray addObject:[NSString stringWithFormat:#"FN:%#", [NSString stringWithFormat:#"%#%#", [Person sharedInstance].firstName, [Person sharedInstance].lastName]]];
[mutableArray addObject:[NSString stringWithFormat:#"TEL:%#",[Person sharedInstance].phone]];
[mutableArray addObject:[NSString stringWithFormat:#"email:%#", [Person sharedInstance].email]];
[mutableArray addObject:[NSString stringWithFormat:#"PHOTO;BASE64;ENCODING=b;TYPE=JPEG:%#",[imageData base64EncodedStringWithOptions:0]]];
[mutableArray addObject:#"END:VCARD"];
return [mutableArray componentsJoinedByString:#"\n"];
}
-(void)emptySandbox
{
NSFileManager *fileMgr = [[NSFileManager alloc] init];
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];
while (files.count > 0) {
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
if (error == nil) {
for (NSString *path in directoryContents) {
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error];
files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];
if (!removeSuccess) {
// Error
}
}
} else {
// Error
}
}
}
I created another thread and its functionality is working well. But only case is in new thread we cannot use UIControllers. As an example I couldn't use UIAlerview in new thread. How can I slove it?
My tried code is bellow.
- (IBAction)btnCopyImage:(id)sender
{
[NSThread detachNewThreadSelector:#selector(DownloadCheck) toTarget:self withObject:nil];
// [self performSelectorOnMainThread:#selector(DownloadCheck) withObject:nil waitUntilDone:NO];
NSLog(#"My name is ");
int sum =0;
for (int i=1; i<=1000; i++)
{
sum =sum+i;
}
NSLog(#"sum %d",sum);
}
-(void)DownloadCheck
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Download"];
NSString* saveDialogURL = #"/Volumes/Inbox/7. Debugging and Troubleshooting.zip";
NSString* fileNameWithExtension = saveDialogURL.lastPathComponent;
NSLog(#"path %# ",fileNameWithExtension);
NSString *pathWithExtention=[NSString stringWithFormat:#"%#/%#", path,fileNameWithExtension];
NSLog(#"path %#",pathWithExtention);
//Remove existing file
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
NSError *error;
[filemgr removeItemAtPath:pathWithExtention error:&error];
//Copy file to i phone created directory
if ([filemgr copyItemAtPath: saveDialogURL toPath: pathWithExtention error: NULL] == YES)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Download"
message:#"Downloaded Sucessfully"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"OK", nil];
[alertView show];
NSLog (#"Copy successful");
}
else
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Download Faild"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"OK", nil];
[alertView show];
NSLog (#"Copy Faild");
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
[self performSelectorOnMainThread:#selector(DownloadCheck) withObject:nil waitUntilDone:NO]; this cannot be used because it's working on same thread.
So what should I do by using same code?
I have this code:
-(IBAction)action2:(id)sender{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Confirm" message:#"If you press of a new group with the name you have set will be created" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles: #"Ok", nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Ok"])
{
NSString *destDir = [NSString stringWithFormat:#"/sandbox/%#/", namegroup.text];
NSString *filename5 = namegroup.text;
NSString *filename6 = #"group";
NSString *filename7 = #"groupdata";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath5 = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:#"%#", filename7]];
NSMutableArray *titles = [NSMutableArray array];
[titles addObject:filename5];
NSMutableArray *keys = [NSMutableArray array];
[keys addObject:filename6];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:titles forKeys:keys];
NSString *jsonString = [dict JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding: NSUTF8StringEncoding];
[jsonData writeToFile: getImagePath5 atomically: YES];
[[self restClient] uploadFile:filename7 toPath:destDir
withParentRev:nil fromPath:getImagePath5];
}
}
If I press Ok button, the code is repeated over and over. how can I repeat it only 1 time??
I found out that there was another alert with the same cancel title, and when this was pressed it re-launched the same code. Thanks however for the help.
I'm testing my in-app purchase in sandbox mode but I dun understand why the in-app purchase alert box keeps popping up even though i've clicked Buy...
On the second time it pops up after i clicked 'Buy', i clicked 'Cancel' and there was an error:
Thread 1:EXC_BAD_ACCESS (code1, address=0x6000008)
My .m:
-(void)updateCredit{
//Adding to plist
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"data.plist"];
NSMutableArray *currPlist = [[NSMutableArray alloc] initWithContentsOfFile: path];
NSString *lastEx = [currPlist objectAtIndex:0];
int lastScore = [[currPlist objectAtIndex:1] intValue];
int numberOfTries = [[currPlist objectAtIndex:2] intValue];
int totalScore = [[currPlist objectAtIndex:3] intValue];
int avg = [[currPlist objectAtIndex:4] intValue];
int credit = [[currPlist objectAtIndex:5] intValue];
credit += 10;
NSMutableArray *updatePlist = [[NSMutableArray alloc] init];
[updatePlist addObject:lastEx];
[updatePlist addObject:[NSNumber numberWithInt:lastScore]];
[updatePlist addObject:[NSNumber numberWithInt:numberOfTries]];
[updatePlist addObject:[NSNumber numberWithInt:totalScore]];
[updatePlist addObject:[NSNumber numberWithInt:avg]];
[updatePlist addObject:[NSNumber numberWithInt:credit]];
[updatePlist writeToFile: path atomically:YES];
}
-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
for (SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchasing:
break;
case SKPaymentTransactionStatePurchased:
[[SKPaymentQueue defaultQueue]finishTransaction:transaction];
[self updateCredit];
[self dismissModalViewControllerAnimated:YES];
break;
case SKPaymentTransactionStateRestored:
[[SKPaymentQueue defaultQueue]finishTransaction:transaction];
break;
case SKPaymentTransactionStateFailed:
if (transaction.error.code != SKErrorPaymentCancelled) {
UIAlertView *alert2 = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Error updating credit" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert2 show];
}
[[SKPaymentQueue defaultQueue]finishTransaction:transaction];
break;
default:
break;
}
}
}