在我的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"}}
答案 0 :(得分:3)
获取文件路径的代码不正确。替换这样的行:
let path = "" + (file?.filePathURL?.description)!
使用:
let path = file?.path
仅供参考 - 永远不要将description
方法用于调试和记录以外的任何其他方法。
免责声明 - 我不能流利使用Swift,因此您可能需要在!
或?
处调整我的答案。