【发布时间】:2015-12-09 21:20:15
【问题描述】:
在我的 iOS 应用程序中,我希望用户能够导出和导入设置文件。 我正在尝试实现导入功能。
我已经给自己发送了一封电子邮件,其中包含设置文件(在 Ubuntu 中创建,带有 UTF8 扩展名,如果重要的话)
我在 pList 中定义了我的文件扩展名 (.inv),如下所示:
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeIconFiles</key>
<array/>
<key>CFBundleTypeName</key>
<string>Stratix Settings File</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>com.invera.settings</string>
</array>
</dict>
</array>
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.data</string>
</array>
<key>UTTypeDescription</key>
<string>Stratix Settings File</string>
<key>UTTypeIdentifier</key>
<string>com.invera.settings</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<string>inv</string>
</dict>
</dict>
</array>
我已经覆盖了 AppDelegate 中的方法:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if launchOptions != nil {
let options = launchOptions! as NSDictionary
let file = options.objectForKey(UIApplicationLaunchOptionsURLKey) as! NSURL?
if file != nil {
let path = "" + (file?.filePathURL?.description)!
((self.window?.rootViewController as! UINavigationController).visibleViewController as! LoginViewController).readSettingsFile(path)
}
}
return true
}
func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
let path = "" + (url.filePathURL?.description)!
((self.window?.rootViewController as! UINavigationController).visibleViewController as! LoginViewController).readSettingsFile(path)
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
let path = "" + (url.filePathURL?.description)!
((self.window?.rootViewController as! UINavigationController).visibleViewController as! LoginViewController).readSettingsFile(path)
return true
}
并在我的 ViewController 中创建了一个读取文件的方法:
func readSettingsFile(filePath : String) {
NSLog("File path : " + filePath)
do{
let content = try String(contentsOfFile: filePath, encoding: NSUTF8StringEncoding)
NSLog(content)
} catch let error as NSError {
print(error)
}
}
但是当我尝试读取该文件时,它却说该文件不存在:
File path : file:///private/var/mobile/Containers/Data/Application/E7076F5B-9131-4253-BAE7-0053CC872C2B/Documents/Inbox/settings-32.inv
Error Domain=NSCocoaErrorDomain Code=260 "The file “settings-32.inv” couldn’t
be opened because there is no such file." UserInfo={
NSFilePath=file:///private/var/mobile/Containers/Data/Application/E7076F5B-9131-4253-BAE7-0053CC872C2B/Documents/Inbox/settings-32.inv,
NSUnderlyingError=0x14ed7760 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
【问题讨论】: