gpt4 book ai didi

cocoa-touch - 从 NSData 创建 NSString 时猜测编码

转载 作者:行者123 更新时间:2023-12-03 16:02:06 25 4
gpt4 key购买 nike

从文件读取 NSString 时,我可以使用 initWithContentsOfFile:usedEncoding:error: ,它会猜测文件的编码。

当我从 NSData 创建它时,我唯一的选择是 initWithData:encoding: ,我必须显式传递编码。当我使用 NSData 而不是文件时,如何可靠地猜测编码?

最佳答案

在 iOS 8 和 OS X 10.10 中,NSString 上有一个新的 API :

Objective-C

+ (NSStringEncoding)stringEncodingForData:(NSData *)data
encodingOptions:(NSDictionary *)opts
convertedString:(NSString **)string
usedLossyConversion:(BOOL *)usedLossyConversion;

swift

open class func stringEncoding(for data: Data,
encodingOptions opts: [StringEncodingDetectionOptionsKey : Any]? = nil,
convertedString string: AutoreleasingUnsafeMutablePointer<NSString?>?,
usedLossyConversion: UnsafeMutablePointer<ObjCBool>?) -> UInt

现在您可以让框架进行猜测,根据我的经验,效果非常好!

来自标题(文档目前没有说明该方法,但在 WWDC Session 204 (page 270) 中正式提到过:

  1. an array of suggested string encodings (without specifying the 3rd option in this list, all string encodings are considered but the ones in the array will have a higher preference; moreover, the order of the encodings in the array is important: the first encoding has a higher preference than the second one in the array)
  2. an array of string encodings not to use (the string encodings in this list will not be considered at all)
  3. a boolean option indicating whether only the suggested string encodings are considered
  4. a boolean option indicating whether lossy is allowed
  5. an option that gives a specific string to substitude for mystery bytes
  6. the current user's language
  7. a boolean option indicating whether the data is generated by Windows

If the values in the dictionary have wrong types (for example, the value of NSStringEncodingDetectionSuggestedEncodingsKey is not an array), an exception is thrown.

If the values in the dictionary are unknown (for example, the value in the array of suggested string encodings is not a valid encoding), the values will be ignored.

示例(Swift):

var convertedString: NSString?
let encoding = NSString.stringEncoding(for: data, encodingOptions: nil, convertedString: &convertedString, usedLossyConversion: nil)

如果您只想要解码后的字符串而不关心编码,您可以删除 let encoding =

关于cocoa-touch - 从 NSData 创建 NSString 时猜测编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1351151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com