Open the external pdf reader - objective-c

My app creates a pdf, that can be opened in the regular menĂ¼ and then viewed, but not in the app. How to programatically open pdf in the ipad reader?

You will have to set the delegate in your header's ViewController:
#interface YourViewController : UIViewController <UIDocumentInteractionControllerDelegate>
Then you'll have to implement this method:
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
return self;
}
And then, when you catch which pdf has to be opened:
NSString *sPathPDF = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"name.pdf"]]; //path example for a local stored pdf
NSURL *urlPDF = [NSURL fileURLWithPath:sPathPDF];
UIDocumentInteractionController *dicPDF = [UIDocumentInteractionController interactionControllerWithURL: urlPDF];
[dicPDF setDelegate:self];
[dicPDF presentPreviewAnimated: YES];

Related

Cannot load files in UIDocumentInteractionController

I am building an app that allows the opening of a PDF, and handles this like so:
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url sourceApplication:(NSString *)source annotation:(id)annotation
{
if (url != nil && [url isFileURL])
{
if ([[url pathExtension] isEqualToString:#"pdf"])
{
FilePreviewViewController *filePreviewController = [[FilePreviewViewController alloc] init];
[filePreviewController setURL:url];
[self.navController pushViewController:filePreviewController animated:NO];
return YES;
}
}
return NO;
}
And then in FilePreviewController.m:
-(void) setURL:(NSURL *) URL
{
self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:URL];
[self.documentInteractionController setDelegate:self];
[self.documentInteractionController presentPreviewAnimated:NO];
}
However, when I open a file and the view transitions, I get these messages:
Unbalanced calls to begin/end appearance transitions for <QLRemotePreviewContentController: 0x1581fe00>.
Couldn't issue file extension for path: /private/var/mobile/Containers/Data/Application/6399D00B-47A1-4F33-B34C-3F0B07B648AE/Documents/Inbox/pdf-8.pdf
And the file itself does not load. I'm not sure what I'm doing wrong because this works fine on the simulator (i.e. the PDF loads and displays perfectly).
use this code to view/read pdf format file.
.h
<UIDocumentInteractionControllerDelegate>
UIDocumentInteractionController *controller;
.m
NSString *File_name=[NSString stringWithFormat:#"%#",URL];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#",docDir,[File_name lastPathComponent]];
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:URL];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (pdfData) {
[pdfData writeToFile:pngFilePath atomically:YES];
controller = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:pngFilePath]];
controller.delegate = self;
CGRect rect = CGRectMake(0, 0, appDelegate.wVal, appDelegate.hVal);
[controller presentOptionsMenuFromRect:rect inView:self.view animated:YES];
}
});
});

Stopping sound in Xcode

Hi all,
Please look at the code below, i want to be able to stop the sound when the same button is clicked, another button is clicked and even when going back to the home screen. Not sure what to do here,
FoxViewController.m
#import "FoxViewController.h"
#import <AVFoundation/AVAudioPlayer.h>
AVAudioPlayer *newPlayer_Fox;
#interface FoxViewController ()
#end
#implementation FoxViewController
-(IBAction) Fox;
{
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: #"new"ofType: #"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
[newPlayer play];
}
- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
FoxViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
AVAudioPlayer *newPlayer;
#interface FoxViewController : UIViewController
-(IBAction)Fox;
#end
Your help is much appreciated, Justin.
Maintain one flag say BOOL soundPlay as global variable in FoxViewController.h file
Now in FoxViewController.m's viewDidLoad method
soundPlay = TRUE;
Action button will be like this:
-(IBAction) Fox;
{
if(soundPlay){
soundPlay = FALSE; //made false for next time another condition will be used.
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: #"new"ofType: #"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
[newPlayer play];
}
else
{
if([newPlayer isPlaying])
{
[newPlayer stop];
}
}
}
For stopping sound in background add this method if not added
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
//stop background sound
if([newPlayer isPlaying])
{
[newPlayer stop];
}
}
Summarizing, the sentence to STOP the sound file is:
AudioServicesDisposeSystemSoundID (soundFileObject);
Explanation (Important to understand):
I have a table view with 18 different sound files. When user select a row must sound the corresponding file and when select another row, it must STOP the previous sound and play other.
All this stuff it is necessary:
1) Add to your project "AudioToolbox.framework" inside "Build Phases", inside "Link Binary With Libraries"
2) In header file (in my project it calls "GenericTableView.h") add these sentences:
#include <AudioToolbox/AudioToolbox.h>
CFURLRef soundFileURLRef;
SystemSoundID soundFileObject;
#property (readwrite) CFURLRef soundFileURLRef;
#property (readonly) SystemSoundID soundFileObject;
3) In implement file (in my project it calls "GenericTableView.m") add these sentences:
#synthesize soundFileURLRef;
#synthesize soundFileObject;
And inside your "Action" implementation or in my case, in:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
//
// That is the question: a way to STOP sound file
//
// -----------------------------------------------------------------------
// Very important to STOP the sound file
AudioServicesDisposeSystemSoundID (soundFileObject);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// In my project "rowText" is a field that save the name of the
// corresponding sound (depending on row selected)
// It can be a string, #"Alarm Clock Bell" in example
// Create the URL for the source audio file.
// URLForResource:withExtension: method is new in iOS 4.0.
NSURL *soundURL = [[NSBundle mainBundle] URLForResource:rowText withExtension:#"caf"];
// Store the URL as a CFURLRef instance
self.soundFileURLRef = (CFURLRef) [soundURL retain];
// Create a system sound object representing the sound file.
AudioServicesCreateSystemSoundID (soundFileURLRef,&soundFileObject);
AudioServicesPlaySystemSound (soundFileObject);
[soundURL release];
}
4) Finally, in the same implement file (in my project it calls "GenericTableView.m"):
- (void)dealloc {
[super dealloc];
AudioServicesDisposeSystemSoundID (soundFileObject);
//CFRelease (soundFileURLRef);
}
I must to comment "CFRelease (soundFileURLRef)" because the App ends unexpectedly when user leaves the table view.
All this code is proportioned by Apple. In this link you can find even a sample code to test directly in your iPhone simulator.
https://developer.apple.com/library/ios/samplecode/SysSound/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008018-Intro-DontLinkElementID_2

How to open a PDF within a Cocoa Application

I would like to open a PDF within a Cocoa application. I tried the following to open the PDF using Preview.
[[NSWorkspace sharedWorkspace] openURL:[NSURL fileURLWithPath:#"filepath"]];
But I would like to open the PDF attached to a window, similar to Xcode's Help window. How do you achieve this using PDFKit?
I imported QuartzFrameWork, and added a PDFView in the xib. The following code did the job for me:
NSURL *url = [NSURL fileURLWithPath:#"filePath"]
PDFDocument *pdfDoc = [[PDFDocument alloc] initWithURL:url];
[_pdfView setDocument:pdfDoc];
You can use PDFView for opening PDF files within your application.
http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Conceptual/PDFKitGuide/PDFKit_Prog_Intro/PDFKit_Prog_Intro.html#//apple_ref/doc/uid/TP40001863-CH203-SW1
in .h file
#interface MyViewController:UIViewController <UIDocumentInteractionControllerDelegate>
#property(nonatomic, retain) UIDocumentInteractionController *documentInteractionController;
in .m file
#synthesize documentInteractionController;
- (void)viewDidLoad{
[super viewDidLoad];
documentInteractionController = [[UIDocumentInteractionController alloc] init];
}
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
return self;
}
-(void) openPdf{
NSString *filePath=filePath = [[NSBundle bundleForClass:[self class]] pathForResource:#"filename" ofType:#"pdf"];
NSURL *URL = [NSURL fileURLWithPath:filePath];
if (URL) {
self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:URL];
[self.documentInteractionController setDelegate:self];
[self.documentInteractionController presentPreviewAnimated:YES];
}
}

WebView doesn't load URL passed from another class

I have two class (AppDelegate and WebViewController) with two nib file: one is the main window and one is a window with WebView. In AppDelegate I have this code to show WebViewController Window at launch:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
self.iTunes = [SBApplication applicationWithBundleIdentifier:#"com.apple.iTunes"];
[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:#selector(receiveNotification:) name:#"com.apple.iTunes.playerInfo" object:nil];
[self.lyricsTextView setAlignment:NSCenterTextAlignment];
[self refreshLyrics];
// Here I show my WebViewController Window
newWebViewController = [[WebViewController alloc] init];
[NSBundle loadNibNamed:#"WebViewWindow" owner:newWebViewController];
}
My WebView initialize itself correctly. In WebViewController I have this code:
- (void)goToURLFromExternal:(NSString *)urlToGo {
NSLog(#"%#", urlToGo);
NSURL *newURL = [[NSURL alloc] initWithString:urlToGo];
NSLog(#"%#", newURL);
NSURLRequest *newRequest = [[NSURLRequest alloc] initWithURL:newURL];
NSLog(#"%#", newRequest);
[self.myWebView.mainFrame loadRequest:newRequest];
}
But when I use from AppDelegate this code:
[newWebViewController goToURLFromExternal:[[urlArray objectAtIndex:0] stringValue]];
my WebView doesn't do anything. The page loaded is still the same.
Here there is the output of console for (void)goToURLFromExternal:(NSString *)urlToGo:
2011-10-04 16:55:54.838 iTunes Lyrics[25379:707] http://lyrics.wikia.com/Cake:Dime
2011-10-04 16:55:54.838 iTunes Lyrics[25379:707] http://lyrics.wikia.com/Cake:Dime
2011-10-04 16:55:54.838 iTunes Lyrics[25379:707] <NSURLRequest http://lyrics.wikia.com/Cake:Dime>
Someone have any idea about to resolve my issue?
Thank you so much!!!
Have you link your WebViewController class with the WebViewWindow.nib?
In The WebViewWindow.nib set the File's Owner Class property to WebViewController.

XCode - Display/delete files from NSDocumentDirectory

My application has a 'Browse' button with these codes that allows user to browse the iPad's photo gallery, select a photo and store it into the application using NSDocumentDirectory.
- (IBAction) BrowsePhoto:(id)sender
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:imagePickerController];
[popover setPopoverContentSize:CGSizeMake(320,320)];
[popover presentPopoverFromRect:CGRectMake(200,200,-100,-100) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
self.popoverController = popover;
[imagePickerController release];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)selectedImage editingInfo:(NSDictionary *)editingInfo
{
[self.popoverController dismissPopoverAnimated:YES];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:#"SavedImage.png"];
UIImage *image = imageView.image;
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
Now i want to include a 'Display' button which displays all the photos from the NSDocumentDirectory in a new view. Was thinking of displaying it in thumbnails and also when an image is tapped, it will have a pop up asking the user to confirm if he/she wants to delete the selected photo. If yes, the photo will be removed from the NSDocumentDirectory.
Is it possible to do this? If it is, mind telling me how to do it and share some sample codes? I'm quite lost as i'm still quite new to programming.
Everything you need to do with files is implemented in system class called NSFileManager.
It's not complicated. Try to read the documentation and google some examples. There is a lot of them, e.g. http://www.theappcodeblog.com/2011/04/04/nsfilemanager-tutorial-create-read-and-delete-a-file/