forked from p2/quicklook-csv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNSString+StringWithContentsOfURLExt.m
46 lines (40 loc) · 1.64 KB
/
NSString+StringWithContentsOfURLExt.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// category + class method
// NSString+StringWithContentsOfURLExt.m
#import "NSString+StringWithContentsOfURLExt.h"
// $ defaults read com.google.code.quicklookcsv tryingTextEncoding
# define KEYTRYINGTEXTENCODING @"tryingTextEncoding"
# define DEFAULTTRYINGTEXTENCODING @"CP932"
// # define DEFAULTTRYINGTEXTENCODING @"ISO-8859-1"
NSStringEncoding getTryingTextEncoding();
CFStringEncoding CFStringEncodingFromEncodingName(NSString *enc_name);
@implementation NSString (StringWithContentsOfURLExt)
+ (NSString*)StringWithContentsOfURLExt:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error
{
NSString *fileString = [NSString stringWithContentsOfURL:url usedEncoding:enc error:error];
if (!fileString) {
*enc = getTryingTextEncoding();
fileString = [NSString stringWithContentsOfURL:url encoding:*enc error:error];
}
return fileString;
}
@end
NSStringEncoding getTryingTextEncoding()
{
CFStringEncoding cf_enc;
NSString *enc_name = [NSUserDefaults.standardUserDefaults stringForKey:KEYTRYINGTEXTENCODING];
if (enc_name) {
cf_enc = CFStringEncodingFromEncodingName(enc_name);
if (cf_enc == kCFStringEncodingInvalidId) enc_name = nil;
}
if (!enc_name) {
enc_name = DEFAULTTRYINGTEXTENCODING;
cf_enc = CFStringEncodingFromEncodingName(enc_name);
[NSUserDefaults.standardUserDefaults setObject:enc_name forKey:KEYTRYINGTEXTENCODING];
[NSUserDefaults.standardUserDefaults synchronize];
}
return CFStringConvertEncodingToNSStringEncoding(cf_enc);
}
CFStringEncoding CFStringEncodingFromEncodingName(NSString *enc_name)
{
return CFStringConvertIANACharSetNameToEncoding((CFStringRef)enc_name);
}