NSOpenPanel on Main-Thread doesn't work - objective-c

I tried to use NSOpenPanel for my program and it doesn't work at all, because the NSOpenpanel doesn't run on the main thread.
Here's my code
NSString *strURL;
NSOpenPanel *fileContents;
NSURL *panelURL;
NSArray *fileTypes = [NSArray arrayWithObjects:#"strings", #"STRINGS", nil];
fileContents = [NSOpenPanel openPanel];
[fileContents setCanChooseDirectories:NO];
[fileContents setCanChooseFiles:YES];
[fileContents setAllowedFileTypes:fileTypes];
[fileContents setAllowsMultipleSelection:NO];
NSInteger openPanelButton = [fileContents runModal];
if(openPanelButton == NSModalResponseOK)
{
panelURL = [fileContents URL];
strURL = panelURL.absoluteString;
}
NSArray *linesReadOnly = [strURL componentsSeparatedByString:#"\n"];
I tried both of the following codes:
[fileContents performSelectorOnMainThread:#selector(runModal) withObject:nil waitUntilDone:YES];
and
dispatch_sync(dispatch_get_main_queue(), ^{
//do UI stuff
});
It just doesn't work at all to get this on the main-thread. What do I do wrong?

You can check the below code.
//Open pannel to select any file or image and send it to server with upload file API
let openPannel: NSOpenPanel = NSOpenPanel()
openPannel.allowsMultipleSelection = true
openPannel.canChooseFiles = true
openPannel.canChooseDirectories = false
openPannel.runModal()
let choosenFile = openPannel.URL
if choosenFile != nil
{
let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,(choosenFile?.pathExtension!)!,
nil)
if UTTypeConformsTo((uti?.takeRetainedValue())!, kUTTypeImage) {
print("This is an image!")
}
else if UTTypeConformsTo((uti?.takeRetainedValue())!, kUTTypeFolder) {
print("This is a folder!")
}
else if UTTypeConformsTo((uti?.takeRetainedValue())!, kUTTypeAliasFile) {
print("This is a zip!")
}
else if UTTypeConformsTo((uti?.takeRetainedValue())!, kUTTypeSpreadsheet) {
print("This is a sheet!")
}
}

Related

Displaying text in text view from NSArray

This method found in the AppDelagate, loads a text file of my choosing and splits the context of the text file into an array.
Im having trouble displaying the contents of the array in my NSScrollview * called self.textView.
I am not sure how to update the text view with each member of the array.
- (IBAction)loadButton:(id)sender {
NSOpenPanel *panel = [NSOpenPanel openPanel];
if ([panel runModal] == NSFileHandlingPanelOKButton) {
NSURL *bookUrl = [panel URL];
NSString *contents = [NSString stringWithContentsOfURL: bookUrl encoding: NSASCIIStringEncoding error: NULL];
NSArray *loadedBook = [contents componentsSeparatedByString:#"#NP#"];
self.textView.value = loadedBook[0];
}
}
The right method is setString:, which is declared in NSText.
your code should be:
- (IBAction)loadButton:(id)sender {
NSOpenPanel *panel = [NSOpenPanel openPanel];
if ([panel runModal] == NSFileHandlingPanelOKButton) {
NSURL *bookUrl = [panel URL];
NSString *contents = [NSString stringWithContentsOfURL: bookUrl encoding: NSASCIIStringEncoding error: NULL];
NSArray *loadedBooks = [contents componentsSeparatedByString:#"#NP#"];
[self.textView setString:bookStr];
}
}
UPDATE
Take a look at this question, to see how to add text to a NSScrollView

NSMutableArray writeToURL:url atomically:YES

I'm trying to create a file with an NSMutableArray with just NSStrings stringWithFormat objects inside, this is what i got:
- (IBAction)CreateMod:(id)sender {
NSLog(#"Finished Button Pressed");
NSString* CustomScript = [NSString stringWithFormat:#"//Made with UltimateMM \n %#",self.CS ];
NSArray* fileTypes = [[NSArray alloc] initWithObjects:#"js", nil];
NSSavePanel *spanel = [NSSavePanel savePanel];
[spanel setCanCreateDirectories:YES];
[spanel setCanSelectHiddenExtension:YES];
[spanel setAllowedFileTypes:fileTypes];
[spanel setTreatsFilePackagesAsDirectories:YES];
[spanel beginSheetModalForWindow:self.SecondaryWindow completionHandler:^(NSInteger result) {
if (result == NSFileHandlingPanelOKButton)
{
NSURL *saveURL = [spanel URL];
NSLog(#"%#", saveURL);
NSError* error = nil;
if(_CST == true) {
NSLog(#"CustomScriptMade");
/*
BOOL didWrite = [CustomScript writeToURL:saveURL atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (didWrite == NO)
{
NSLog(#"CustomScript Write Error");
}
*/
}
if(_TTT == true) {
NSLog(#"TopicMade");
BOOL didWrite = [_TopicPR writeToURL:saveURL atomically:YES];
if (didWrite == NO)
{
NSLog(#"Topic Write Error");
}
}
_CST = false;
_TTT = false;
}
}];
}
I have the CustomScript writeToURL out so i can see if it crates the TopicPR, but it doesn't even open the NSSavePanel, Please Help.
thanks in advance!..

PDFDocument writeToURL not working

I am working with PDFDocument and PDFView.
I'm able to open a file and display it.
But if I try to save it with a different URL via PDFDocument's "writeToURL:" it doesn't work.
I logged the fileURL in the console, which was exactly the same like I typed in the save-Panel. But it doesn't write the Document to that URL.
I tried the same with a new allocated PDFDocument, which was working like i expected it.
Do I forget about any access-issues?
Here's my code:
NSURL* fileURL = [[NSURL alloc] init];
NSSavePanel* savePanel;
savePanel = [NSSavePanel savePanel];
NSArray* fileTypes = [[NSArray alloc] initWithObjects:#"pdf", nil];
[savePanel setAllowedFileTypes:fileTypes];
if([savePanel runModal] == NSFileHandlingPanelOKButton)
{
fileURL = savePanel.URL;
}
else
{
NSLog(#"failed to save file");
fileURL = nil;
}
[pdfView.document writeToURL:fileURL];
Thanks in advance

Calling methods after comparing string objects from NSArray Cocoa

I am selecting files through this code:
- (IBAction)selectFile:(id)sender {
// Create the File Open Dialog class.
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setPrompt:#"Select"];
fileTypes = [NSArray arrayWithObjects:#"wmv", #"3gp", #"mp4", #"avi", #"mp3", #"mma", #"wav", #"jpeg", #"png", #"jpg", #"tiff", nil];
// NSArray *JpegfileTypes = [NSArray arrayWithObjects:#"jpeg", #"png", #"jpg", #"tiff", #"mp3" nil];
// Enable the selection of files in the dialog.
[openDlg setCanChooseFiles:YES];
//Enable multiple selection of files
[openDlg setAllowsMultipleSelection:YES];
// Enable the selection of directories in the dialog.
[openDlg setCanChooseDirectories:YES];
// Display the dialog. If the OK button was pressed,
// process the files.
if ( [openDlg runModalForDirectory:nil file:nil types:fileTypes] == NSOKButton )
{
// Get an array containing the full filenames of all
// files and directories selected.
files = [[openDlg filenames] retain];
int i; // Loop counter.
// Loop through all the files and process them.
for( i = 0; i < [files count]; i++ )
{
NSString *tempFilePath = [files objectAtIndex:i];
NSLog(#"tempFilePath::: %#",tempFilePath);
inputFilePath = [[files objectAtIndex:i] retain];
NSLog(#"filename::: %#", inputFilePath);
// Do something with the filename.
[selectedFile setStringValue:inputFilePath];
NSLog(#"selectedFile:::: %#", selectedFile);
}
}
}
Then after selection I have used this code to process the selected file.
- (IBAction)setMessage:(id)sender {
[fileGenProgress startAnimation:self];
NSString *message = [[NSString alloc] initWithFormat:#"Started"];
[lblMessage setStringValue:message];
[message release];
[self startProcessingVideoFile];
[self startProcessingAudioFile];
[self startProcessingJpg];
}
The issue I am facing is that, I am not getting that how would I compare the different strings like if the selected file was 3gp/mp4 or jpg or mp3. As if user has selected some video file then the method [self startProcessingVideoFile]; will run and if he has selected some JPG or PNG etc file then [self startProcessingAudioFile]; method will run.
As selected will be having a path not only the extension of the file. So in this scenario how can I force the - (IBAction)setMessage:(id)sender method to run the appropriate method.
You can get string's extension (format) like this:
NSString *extension = [stringPath pathExtension];
And for comparing now it's very easy when You know what extension Your file is. For example:
NSLog(extension);
if ([extension isEqualToString:#"3gp"] || [ext isEqualToString:#"mp4"]) {
[self startProcessingVideoFile];
}
and etc.
Update:
Your IBAction:SetMessage should look like this:
- (IBAction)setMessage:(id)sender {
[fileGenProgress startAnimation:self];
NSString *message = [[NSString alloc] initWithFormat:#"Started"];
[lblMessage setStringValue:message];
[message release];
NSString *extension = [inputFilePath pathExtension];
NSLog(extension);
if ([extension isEqualToString:#"3gp"] || [ext isEqualToString:#"mp4"]) {
[self startProcessingVideoFile];
}
// And etc for others formats.
//[self startProcessingAudioFile];
//[self startProcessingJpg];
}

Add item from finder

I have a table with the classic + - buttons underneath it. (on mac)
I want to press the + button, and open a little finder to select a file, to add it on the table.
How can I do that?
I searched the developer reference, but didn't find it..
Use NSOpenPanel.
For a guide on dealing with files and using open panels, see the Application File Management guide.
For instance:
- (IBAction)addFile:(id)sender
{
NSInteger result;
NSArray *fileTypes = [NSArray arrayWithObject:#"html"];
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
[oPanel setAllowsMultipleSelection:YES];
[oPanel setDirectory:NSHomeDirectory()];
[oPanel setCanChooseDirectories:NO];
result = [oPanel runModal];
if (result == NSFileHandlingPanelOKButton) {
for (NSURL *fileURL in [oPanel URLs]) {
// do something with fileURL
}
}
}
Another example using a sheet:
- (IBAction)addFile:(id)sender
{
NSArray *fileTypes = [NSArray arrayWithObject:#"html"];
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
[oPanel setAllowsMultipleSelection:YES];
[oPanel setDirectory:NSHomeDirectory()];
[oPanel setCanChooseDirectories:NO];
[oPanel beginSheetModalForWindow:[self window]
completionHandler:^(NSInteger result) {
if (result == NSFileHandlingPanelOKButton) {
for (NSURL *fileURL in [oPanel URLs]) {
// do something with fileURL
}
}
}];
}