Objective c OSX应用程序,获取用户使用NSOpenPanel选择的文件数据
我是开发Objective c OSX应用程序,获取用户使用NSOpenPanel选择的文件数据,objective-c,macos,cocoa,Objective C,Macos,Cocoa,我是开发OSX应用程序的新手。我通常会做iOS应用程序,所以很多概念都会延续下来。然而,我似乎不太明白为什么我不能在我的系统上检索文件的数据 要读取用户系统上的文件,是否需要先执行某些操作 以下是我所拥有的: - (IBAction)btnBrowse:(id)sender { NSOpenPanel *panel = [NSOpenPanel openPanel]; [panel beginWithCompletionHandler:^(NSInteger result){
OSX
应用程序的新手。我通常会做iOS应用程序,所以很多概念都会延续下来。然而,我似乎不太明白为什么我不能在我的系统上检索文件的数据
要读取用户系统上的文件,是否需要先执行某些操作
以下是我所拥有的:
- (IBAction)btnBrowse:(id)sender {
NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel beginWithCompletionHandler:^(NSInteger result){
if (result == NSFileHandlingPanelOKButton) {
//Get the file url user selected
NSURL *file = [[panel URLs] objectAtIndex:0];
//Get the file data
NSError *error;
NSString *fileData = [NSString stringWithContentsOfFile:[NSString stringWithFormat:@"%@", file] encoding:NSUTF8StringEncoding error:&error];
//This returns null
NSLog(@"%@", fileData);
//This says that the file does not exist
NSLog(@"Error: %@", error.localizedDescription);
}
}];
}
使用
-[NSURL path]
方法而不是直接调用'file',因为它是一个NSURL,而不是NSString。使用-[NSURL path]
方法而不是直接调用'file',因为它是一个NSURL,而不是NSString。NSOpenPanel
返回NSURL
对象,最简单的解决方案是使用NSURL
相关API
NSString *fileData = [NSString stringWithContentsOfURL:file encoding:NSUTF8StringEncoding error:&error];
如果您不知道文本编码,可以使用此API,如果读取成功,encoding
包含使用的编码
NSStringEncoding encoding;
NSString *fileData = [NSString stringWithContentsOfURL:file usedEncoding:&encoding error:&error];
NSOpenPanel
返回NSURL
对象,最简单的解决方案是使用NSURL
相关API
NSString *fileData = [NSString stringWithContentsOfURL:file encoding:NSUTF8StringEncoding error:&error];
如果您不知道文本编码,可以使用此API,如果读取成功,encoding
包含使用的编码
NSStringEncoding encoding;
NSString *fileData = [NSString stringWithContentsOfURL:file usedEncoding:&encoding error:&error];
是的,我想了很多,但是我现在遇到了一个不同的问题,我试图打开的文件类型是
csv
。我收到以下错误:无法打开文件“file.csv”,因为无法确定其内容的文本编码。
。您能帮忙吗?然后您必须检查其他编码,如nsascistringencoding
或nsisolatin1stringecoding
nsascistringencoding
。谢谢。是的,我想了很多,但是我现在遇到了一个不同的问题,我试图打开的文件类型是csv
。我收到以下错误:无法打开文件“file.csv”,因为无法确定其内容的文本编码。
。您能帮忙吗?然后您必须检查其他编码,如nsascistringencoding
或nsisolatin1stringecoding
nsascistringencoding
。谢谢