swift - 为什么使用 NetFSMountURLSync 的命令行参数中的瑞典语字符不起作用?

标签 swift xcode macos

我尝试了我的第一个 Swift 程序。它旨在从带有参数和安装服务器卷的 shell 脚本运行。当我从 Xcode 启动程序时,在卷名称(例如,å、ä、ö)中使用带有瑞典字符的参数,该程序可以正常工作。如果我从命令行启动程序,并在卷名称中使用带有瑞典字符的参数,则安装失败,它会在安装点创建一个文件夹,并在“/Volumes”中使用正确的名称。

为什么带有瑞典字符的参数在命令行中不起作用?

代码:

import Foundation
import NetFS

func mountShare(serverAddress: String, shareName: String, userName: String, password: String) {
    let fm = FileManager.default
    let mountPoint = "/Volumes/".appendingFormat(shareName)
    var isDir : ObjCBool = false
    if fm.fileExists(atPath: mountPoint, isDirectory: &isDir) {
        if isDir.boolValue {
            unmount(mountPoint, 0)
            print("Unmounted: \(mountPoint)")
        }
    }
    let sharePathRaw = "\(serverAddress)/\(shareName)"
    let sharePathWithPercentEscapes = sharePathRaw.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
    let sharePath = NSURL(string: sharePathWithPercentEscapes!)
    let kNAUIOptionKey = "UIOption"
    let kNAUIOptionNoUI = "NoUI"
    let mount_options = NSMutableDictionary()
    mount_options[kNAUIOptionKey] = kNAUIOptionNoUI
    NetFSMountURLSync(sharePath as CFURL!, nil, userName as CFString!, password as CFString!, mount_options, nil, nil)
}

let argCount = CommandLine.argc
if argCount == 5 {
    let serverUrl = CommandLine.arguments[1]
    let shareName = CommandLine.arguments[2]
    let userName = CommandLine.arguments[3]
    let password = CommandLine.arguments[4]
    mountShare(serverAddress: "\(serverUrl)", shareName: "\(shareName)", userName: "\(userName)", password: "\(password)")
} else {
    print("Wrong number of arguments.")
}

从命令行启动程序的示例:

mountVolume "afp://my.server.com" "myVolume" "user" "password"

从命令行启动程序的示例不起作用:

mountVolume "afp://my.server.com" "myVolumeÅÄÖ" "user" "password"

更多信息: 当我从 Xcode 替代命令行运行程序时,我试图打印出所有用于比较值的变量,但没有区别。但是,NetFSMountURLSync 在命令行上以代码 2 而不是 0 退出。

最佳答案

如果在将连接字符串传递给 NSURL 的 init 之前首先转义连接字符串相关部分中的所有特殊字符,是否可行?

let encodedShareName = shareName.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
let sharePathRaw = "\(serverAddress)/\(encodedShareName!)"

关于swift - 为什么使用 NetFSMountURLSync 的命令行参数中的瑞典语字符不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40452115/

相关文章:

iphone - 识别字符/手写字符

xcode - 如何在主项目Xcode 4.1中包含 bundle 软件

macos - 如何在 OSX 上安装特定的 clang 版本?

ios - 在SpriteKit中使用UIInterpolatingMotionEffect?

Swift Firestore 检索数据

ios - SpriteKit 中的 FPS 下降

swift - 从 swift 运行一个 .sh 文件?

ios - Xcode 6 中的可编辑多行文本输入

macos - 可用性:mac 用户理解 "right-click"吗?

ios - 用于 iOS 和 OS X 开发的共享代码库