为什么swift5不支持导入文件的类型?
Why don't support the type of imported file in swift5?
我是 iOS 的开发者。我目前正在制作一个加密钱包。加载 keystore
文件类型时不支持的问题。我将 Info.list
文件中的数据类型保存为 public.data
以扩大范围。我可以选择一个文件,但我在加载它时没有传递它。有什么问题吗?
DocumentBrowserViewController.swift
class DocumentBrowserViewController : UIDocumentBrowserViewController, UIDocumentBrowserViewControllerDelegate {
...
func presentDocument(at documentURL: URL) throws {
// Start accessing a security-scoped resource.
guard documentURL.startAccessingSecurityScopedResource() else {
throw IXError.fileAcessFailed
}
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let documentViewController = storyBoard.instantiateViewController(withIdentifier: "MainViewController") as! MainViewController
documentViewController.document = Document(fileURL: documentURL)
present(documentViewController, animated: true, completion: nil)
Log.Debug(documentURL)
defer { documentURL.stopAccessingSecurityScopedResource() }
}
Document.swift
import UIKit
class Document: UIDocument {
var fileData: Data?
var filesText: ****.Wallet?
override func contents(forType typeName: String) throws -> Any {
Log.Debug("**********************************************************")
if typeName == "public.data" {
if let content = filesText {
let data = content
return data
} else {
return Data()
}
} else {
Log.Debug("**********************************************************")
return Data()
}
} // end func contents
override func load(fromContents contents: Any, ofType typeName: String?) throws {
if let fileType = typeName {
if fileType == "public.png" || fileType == "public.jpeg" { // .jpg not recognized
if let fileContents = contents as? Data {
fileData = fileContents
}
} else if fileType == "public.data" {
if let fileContents = contents as? ***.Keystore {
// filesText = String(data: fileContents, encoding: .utf8)
filesText = ***.Wallet.init(keystore: fileContents)
}
} else {
Log.Debug("**********************************************************")
print("File type unsupported.") // Keystore file here
}
} // end if let fileType = typeName
} // end func load
public var state: String {
switch documentState {
case .normal:
return "Normal"
case .closed:
return "Closed"
case .inConflict:
return "Conflict"
case .savingError:
return "Save Error"
case .editingDisabled:
return "Editing Disabled"
case .progressAvailable:
return "Progress Available"
default:
return "Unknown"
}
} // end public var state
} // end class Document
MainController.swift
document?.open(completionHandler: { (success) in
if success {
if self.document?.fileType == "public.png" || self.document?.fileType == "public.jpeg" {
// self.imageView.image = UIImage(data: (self.document?.fileData)!)
Log.Debug("#################################################")
print("\(String(describing: self.document?.fileData))")
Log.Debug("#################################################")
// #4.5 - If the UIDocument reports that it is a text file...
} else if self.document?.fileType == "public.data" {
// self.textView.text = self.document?.filesText!
Log.Debug("**********************************************************")
print("\(String(describing: self.document?.filesText))")
Log.Debug("**********************************************************")
}
Log.Debug("**********************************************************")
print("\(String(describing: self.document?.fileURL.lastPathComponent))")
Log.Debug("**********************************************************")
print("Document state: \((self.document?.state)!)")
Log.Debug("**********************************************************")
} else {
// Make sure to handle the failed import appropriately, e.g., by presenting an error message to the user.
}
})
Info.list
文件网址
file:///Users/******/Library/Developer/CoreSimulator/Devices/15169C47-DC68-4B14-B8E8-F75E4108AB7A/data/Containers/Data/Application/499E0805-A3AE-4312-B8B4-55236CFC7BD8/Documents/***/******
内容:
Document.swift load(fromContents:ofType:) [Line:69] <7b226164
64726573 73223a22 64616361 66333634 35393939 36323366 32383535
65636262 36393661 ... >
类型名称:
load(fromContents:ofType:) [Line:71]
Optional("dyn.ah62d4rv4ge8xeqbwtk0w43dbqru0qq30gu4xwsm3g23dg3vwha4xn3pdqmvdqsm0qe6xgqbuqu6ds2mwqmw0q2v2he")
此文件不符合这两个条件中的任何一个。我的文件必须通过“public.data
”条件。我做错了什么?
************************************************ * 编辑 *************************
Info.list
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeIconFiles</key>
<array/>
<key>CFBundleTypeName</key>
<string>images</string>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>LSHandlerRank</key>
<string>Alternate</string>
<key>LSItemContentTypes</key>
<array>
<string>public.image</string>
</array>
</dict>
<dict>
<key>CFBundleTypeIconFiles</key>
<array/>
<key>CFBundleTypeName</key>
<string>data</string>
<key>LSHandlerRank</key>
<string>Alternate</string>
<key>LSItemContentTypes</key>
<array>
<string>public.data</string>
</array>
</dict>
</array>
针对 typeName
的硬编码相等性检查是你出错的地方。
如您所见,您的文件没有文件扩展名。文件扩展名是系统用于确定系统上特定文件的通用类型标识符 (UTI) 的唯一真实来源。
没有文件扩展名,我认为系统会将整个文件名视为扩展名。鉴于没有列出使用与您的文件名匹配的扩展名的 UTI (0ec6dcc292ec87067774805cb63a4c4694a35e33
),系统会在遇到没有注册 UTI 的扩展名时执行它总是做的事情:它会创建一个动态 UTI。
动态 UTI 以 "dyn."
开头,后面跟着一些看似随意的字符,实际上是对未注册 UTI 的已知元数据(文件扩展名、MIME 类型、OSType、PastboardTypes 等)的编码。
你的错误源于对 typeName
:
的精确匹配
if typeName == "public.data" {
// ...
}
鉴于 typeName
的值为 dyn.ah62d4rv4ge8xeqbwtk0w43dbqru0qq30gu4xwsm3g23dg3vwha4xn3pdqmvdqsm0qe6xgqbuqu6ds2mwqmw0q2v2he
,这显然会失败。
相反,您应该检查一致性:
import Foundation
import CoreServices
// A helper function to hide away the CFString bridging cruft
func uti(_ uti: String, conformsTo candidateParent: String) -> Bool {
return UTTypeConformsTo(uti as CFString, candidateParent as CFString)
}
// ...
if uti(typeName, conformsTo: "public.data") {
// ...
}
我是 iOS 的开发者。我目前正在制作一个加密钱包。加载 keystore
文件类型时不支持的问题。我将 Info.list
文件中的数据类型保存为 public.data
以扩大范围。我可以选择一个文件,但我在加载它时没有传递它。有什么问题吗?
DocumentBrowserViewController.swift
class DocumentBrowserViewController : UIDocumentBrowserViewController, UIDocumentBrowserViewControllerDelegate {
...
func presentDocument(at documentURL: URL) throws {
// Start accessing a security-scoped resource.
guard documentURL.startAccessingSecurityScopedResource() else {
throw IXError.fileAcessFailed
}
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let documentViewController = storyBoard.instantiateViewController(withIdentifier: "MainViewController") as! MainViewController
documentViewController.document = Document(fileURL: documentURL)
present(documentViewController, animated: true, completion: nil)
Log.Debug(documentURL)
defer { documentURL.stopAccessingSecurityScopedResource() }
}
Document.swift
import UIKit
class Document: UIDocument {
var fileData: Data?
var filesText: ****.Wallet?
override func contents(forType typeName: String) throws -> Any {
Log.Debug("**********************************************************")
if typeName == "public.data" {
if let content = filesText {
let data = content
return data
} else {
return Data()
}
} else {
Log.Debug("**********************************************************")
return Data()
}
} // end func contents
override func load(fromContents contents: Any, ofType typeName: String?) throws {
if let fileType = typeName {
if fileType == "public.png" || fileType == "public.jpeg" { // .jpg not recognized
if let fileContents = contents as? Data {
fileData = fileContents
}
} else if fileType == "public.data" {
if let fileContents = contents as? ***.Keystore {
// filesText = String(data: fileContents, encoding: .utf8)
filesText = ***.Wallet.init(keystore: fileContents)
}
} else {
Log.Debug("**********************************************************")
print("File type unsupported.") // Keystore file here
}
} // end if let fileType = typeName
} // end func load
public var state: String {
switch documentState {
case .normal:
return "Normal"
case .closed:
return "Closed"
case .inConflict:
return "Conflict"
case .savingError:
return "Save Error"
case .editingDisabled:
return "Editing Disabled"
case .progressAvailable:
return "Progress Available"
default:
return "Unknown"
}
} // end public var state
} // end class Document
MainController.swift
document?.open(completionHandler: { (success) in
if success {
if self.document?.fileType == "public.png" || self.document?.fileType == "public.jpeg" {
// self.imageView.image = UIImage(data: (self.document?.fileData)!)
Log.Debug("#################################################")
print("\(String(describing: self.document?.fileData))")
Log.Debug("#################################################")
// #4.5 - If the UIDocument reports that it is a text file...
} else if self.document?.fileType == "public.data" {
// self.textView.text = self.document?.filesText!
Log.Debug("**********************************************************")
print("\(String(describing: self.document?.filesText))")
Log.Debug("**********************************************************")
}
Log.Debug("**********************************************************")
print("\(String(describing: self.document?.fileURL.lastPathComponent))")
Log.Debug("**********************************************************")
print("Document state: \((self.document?.state)!)")
Log.Debug("**********************************************************")
} else {
// Make sure to handle the failed import appropriately, e.g., by presenting an error message to the user.
}
})
Info.list
文件网址
file:///Users/******/Library/Developer/CoreSimulator/Devices/15169C47-DC68-4B14-B8E8-F75E4108AB7A/data/Containers/Data/Application/499E0805-A3AE-4312-B8B4-55236CFC7BD8/Documents/***/******
内容:
Document.swift load(fromContents:ofType:) [Line:69] <7b226164 64726573 73223a22 64616361 66333634 35393939 36323366 32383535 65636262 36393661 ... >
类型名称:
load(fromContents:ofType:) [Line:71] Optional("dyn.ah62d4rv4ge8xeqbwtk0w43dbqru0qq30gu4xwsm3g23dg3vwha4xn3pdqmvdqsm0qe6xgqbuqu6ds2mwqmw0q2v2he")
此文件不符合这两个条件中的任何一个。我的文件必须通过“public.data
”条件。我做错了什么?
************************************************ * 编辑 *************************
Info.list
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeIconFiles</key>
<array/>
<key>CFBundleTypeName</key>
<string>images</string>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>LSHandlerRank</key>
<string>Alternate</string>
<key>LSItemContentTypes</key>
<array>
<string>public.image</string>
</array>
</dict>
<dict>
<key>CFBundleTypeIconFiles</key>
<array/>
<key>CFBundleTypeName</key>
<string>data</string>
<key>LSHandlerRank</key>
<string>Alternate</string>
<key>LSItemContentTypes</key>
<array>
<string>public.data</string>
</array>
</dict>
</array>
针对 typeName
的硬编码相等性检查是你出错的地方。
如您所见,您的文件没有文件扩展名。文件扩展名是系统用于确定系统上特定文件的通用类型标识符 (UTI) 的唯一真实来源。
没有文件扩展名,我认为系统会将整个文件名视为扩展名。鉴于没有列出使用与您的文件名匹配的扩展名的 UTI (0ec6dcc292ec87067774805cb63a4c4694a35e33
),系统会在遇到没有注册 UTI 的扩展名时执行它总是做的事情:它会创建一个动态 UTI。
动态 UTI 以 "dyn."
开头,后面跟着一些看似随意的字符,实际上是对未注册 UTI 的已知元数据(文件扩展名、MIME 类型、OSType、PastboardTypes 等)的编码。
你的错误源于对 typeName
:
if typeName == "public.data" {
// ...
}
鉴于 typeName
的值为 dyn.ah62d4rv4ge8xeqbwtk0w43dbqru0qq30gu4xwsm3g23dg3vwha4xn3pdqmvdqsm0qe6xgqbuqu6ds2mwqmw0q2v2he
,这显然会失败。
相反,您应该检查一致性:
import Foundation
import CoreServices
// A helper function to hide away the CFString bridging cruft
func uti(_ uti: String, conformsTo candidateParent: String) -> Bool {
return UTTypeConformsTo(uti as CFString, candidateParent as CFString)
}
// ...
if uti(typeName, conformsTo: "public.data") {
// ...
}