Displaying text in text view from NSArray - objective-c

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

Related

NSOpenPanel on Main-Thread doesn't work

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!")
}
}

Objective C how to print and NSArray of strings into an NScrollView and NSTextField

I am making a simple gui on Xcode. I use a button to load a text file into an NSArray like below.
NSOpenPanel *panel = [NSOpenPanel openPanel];
if ([panel runModal] == NSFileHandlingPanelOKButton) {
albumURL = [panel URL];
info = [NSString stringWithContentsOfURL: albumURL encoding: NSASCIIStringEncoding error: NULL];
listItems = [info componentsSeparatedByString:#"\n"];
NSString *combinedString = [listItems componentsJoinedByString:#"\n"];
//[self.TrackList setValue:combinedString forKey: combinedString];
}
I want to print the contents of the array into the NSscrollview as a series of strings. I also want to print the context of some specific index into different textfields.
So far I only managed to figure out how to put a set string into the textfield like below.
[self.myTextField setStringValue:#"My string of whatever"];
I'm new to this stuff so if you need more info please ask.

Open a document with Objective-C for an OS X application

I've implemented a simple application that basically outputs informations about a given triangle (see image). I've created the triangles programmatically. I would like to improve this example providing a mechanism to open a say .tri file with its sides (e.g. 3 4 5). How can I achieve that ? I've done some research and found out there's a method called openDocument.. How would I use this on my application ? Can someone give me an example of how to achieve that ? Apparently it's not a document-based application.. I've got this code on github: https://github.com/mcand/TableViewMacExample.
I managed to make the panel appear like below.
- (IBAction)openDocument:(id)sender{
NSOpenPanel* openPanel = [NSOpenPanel openPanel];
[openPanel setAllowedFileTypes:[NSArray arrayWithObjects:#"tri", #"qua",nil]];
[openPanel runModal];
}
After opening the file, I cannot change the values of my NSTableView. The code is like that:
- (IBAction)openDocument:(id)sender{
NSOpenPanel* panel = [NSOpenPanel openPanel];
[panel setAllowedFileTypes:[NSArray arrayWithObjects:#"tri", #"qua",nil]];
[panel beginWithCompletionHandler:^(NSInteger result){
if (result == NSFileHandlingPanelOKButton) {
NSURL* file = [[panel URLs] objectAtIndex:0];
[self performSelectorInBackground:#selector(triangle:) withObject:file];
}
}];
}
-(void) triangle:(NSURL *)file{
NSError *error;
NSString *words = [[NSString alloc] initWithContentsOfURL:file encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", words);
NSArray* lines = [words componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableArray *shapes = [[NSMutableArray alloc] init];
while (lines) {
NSArray*info = [words componentsSeparatedByString:#";"];
// Creates triangles to be populated
CGFloat side1 = (CGFloat)[info[0] floatValue];
CGFloat side2 = (CGFloat)[info[1] floatValue];
CGFloat side3 = (CGFloat)[info[2] floatValue];
Triangle *triangle = [[Triangle alloc] initWithSides:side1 side:side2 andSide:side3];
[shapes addObject:triangle];
}
self.formsArray = shapes;
[self performSelectorOnMainThread:#selector(updateTableView) withObject:nil waitUntilDone:YES];
}
-(void)updateTableView{
[self.tableView reloadData];
}
#end

NSOpenPanel not correctly accessing NSUrl from filename with Whitespace

Did a search, didn't find any issues on this.
My application takes .csv files, switches the data around and spits it out in a way my company finds useful. The issue is that the program seems to require filenames without whitespace. For instance "My data.csv" will not work, but "My_data.csv" will work. Here is what I believe to be the relevant code
NSArray *allowedTypes = [NSArray arrayWithObjects:#"CSV",#"csv",nil];
openDLG = [NSOpenPanel openPanel];
[openDLG setDelegate:self];
[openDLG setCanChooseFiles:YES];
[openDLG setAllowedFileTypes:allowedTypes];
NSInteger openReturn = [openDLG runModal];
if (openReturn == NSFileHandlingPanelOKButton) {
NSArray *rawCSVs = [openDLG URLs];
NSEnumerator *enumerator = [rawCSVs objectEnumerator];
id object;
while ((object = [enumerator nextObject])) {
NSString *tempDump = [NSString stringWithContentsOfURL:object encoding:NSUTF8StringEncoding error:NULL];
NSArray *bigArray = [tempDump csvRows];
int total = [bigArray count];
....do other things
In debug mode, the "object" comes up as nil for filenames with whitespace and "tempdump" string comes up as #"nil" for filenames with whitespace, but comes up wonderfully for names_with_underscores
An URL does not permit every character, so you will need to do some conversion.
NSString *rawString = [NSString stringWithString:#"/Users/myusername/test 1.txt"];
NSString *escapedString = [rawString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:escapedString];
NSLog(#"url: %#", url);

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];
}