StringByAppendingPathComponent 不可用

我的应用程序在 Instagram 上分享照片,为了做到这一点,它首先将照片保存在一个临时目录中:

let writePath = NSTemporaryDirectory().stringByAppendingPathComponent("instagram.igo")

它在 Swift 1.2上工作,但在 Swift 2.0上不工作。

给定的错误消息是:

StringByAppendingPathComponent 不可用: 请在 NSURL 上使用 URLByAppendingPathComponent。

73265 次浏览

它适用于 NSString,所以你可以这样使用它:

extension String {
func stringByAppendingPathComponent(path: String) -> String {
let nsSt = self as NSString
return nsSt.stringByAppendingPathComponent(path)
}
}

现在您可以使用这个扩展,它将首先将您的 String转换为 NSString,然后执行操作。

你的代码是:

let writePath = NSTemporaryDirectory().stringByAppendingPathComponent("instagram.igo")

下面是其他一些使用方法:

extension String {


var lastPathComponent: String {
return (self as NSString).lastPathComponent
}
var pathExtension: String {
return (self as NSString).pathExtension
}
var stringByDeletingLastPathComponent: String {
return (self as NSString).stringByDeletingLastPathComponent
}
var stringByDeletingPathExtension: String {
return (self as NSString).stringByDeletingPathExtension
}
var pathComponents: [String] {
return (self as NSString).pathComponents
}
func stringByAppendingPathComponent(path: String) -> String {
let nsSt = self as NSString
return nsSt.stringByAppendingPathComponent(path)
}
func stringByAppendingPathExtension(ext: String) -> String? {
let nsSt = self as NSString
return nsSt.stringByAppendingPathExtension(ext)
}
}

来自 给你的参考文献。

对于 Swift 3.0:

extension String {
func stringByAppendingPathComponent1(path: String) -> String {
let nsSt = self as NSString
return nsSt.appendingPathComponent(path)
}
}


let writePath = NSTemporaryDirectory().stringByAppendingPathComponent(path: "instagram.igo")




extension String {


var lastPathComponent: String {
return (self as NSString).lastPathComponent
}
var pathExtension: String {
return (self as NSString).pathExtension
}
var stringByDeletingLastPathComponent: String {
return (self as NSString).deletingLastPathComponent
}
var stringByDeletingPathExtension: String {
return (self as NSString).deletingPathExtension
}
var pathComponents: [String] {
return (self as NSString).pathComponents
}
func stringByAppendingPathComponent(path: String) -> String {
let nsSt = self as NSString
return nsSt.appendingPathComponent(path)
}
func stringByAppendingPathExtension(ext: String) -> String? {
let nsSt = self as NSString
return nsSt.appendingPathExtension(ext)
}
}

在 Swift 2.0中,stringByAppendingPathComponent方法似乎被删除了,因此错误消息建议使用:

let writePath = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("instagram.igo")

更新:

URLByAppendingPathComponent()已被 appendingPathComponent()取代,所以改为:

let writePath = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("instagram.igo")

只需将字符串包装为 NSString

let writePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("instagram.igo")

做以下事情:

(("\(fileName)" as NSString).lastPathComponent as NSString).stringByDeletingPathExtension

为了迅捷2.0

// Get the documents Directory
func documentsDirectory() -> String {
let documentsFolderPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
return documentsFolderPath
}


// Get path for a file in the directory
func fileInDocumentsDirectory(filename: String) -> String {


let writePath = (documentsDirectory() as NSString).stringByAppendingPathComponent("Mobile")


if (!NSFileManager.defaultManager().fileExistsAtPath(writePath)) {
do {
try NSFileManager.defaultManager().createDirectoryAtPath(writePath, withIntermediateDirectories: false, attributes: nil) }
catch let error as NSError {
print(error.localizedDescription);
}
}
return (writePath as NSString).stringByAppendingPathComponent(filename)
}


//# MARK: - Save Image in Doc dir
func saveImage (image: UIImage, path: String ) -> Bool{


let pngImageData = UIImagePNGRepresentation(image)
//        let jpgImageData = UIImageJPEGRepresentation(image, 1.0)   // if you want to save as JPEG
let result = pngImageData!.writeToFile(path, atomically: true)


print("\(result)")
print("\(path)")


return result


}

您可以改用 URLByAppendingPathComponent ()。请注意,您应该修剪路径字符串以删除“ file://”前缀:

let uniqueFileName = NSUUID().UUIDString
let documentsDirectory = getDocumentsDirectoryURL()
if let path = documentsDirectory?.URLByAppendingPathComponent(uniqueFileName) {
var pathString = path.absoluteString
pathString = imagePathString.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "file://"))
}


func getDocumentsDirectoryURL() -> NSURL? {
let fileManager = NSFileManager()
if let docsDirectory = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first {
return docsDirectory
}
return nil
}

Swift 3:

let writePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(directoryname).path

或者最好创建这个扩展:

extension String {
func appendingPathComponent(_ string: String) -> String {
return URL(fileURLWithPath: self).appendingPathComponent(string).path
}
}

用途:

 let writePath = NSTemporaryDirectory().appendingPathComponent(directoryname)

Swift 3解决方案:

下面是一个获取文档目录路径的函数-

    func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in:.userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}

使用方法:

    getDocumentsDirectory.appendingPathComponent("google.com")

结果:

    file:///var/folders/w1/3rcp2fvs1qv43hfsh5876s0h0000gn/T/com.apple.dt.Xcode.pg/containers/com.apple.dt.playground.stub.iOS_Simulator.MyPlayground-7CF9F706-509C-4D4C-997E-AB8FE9E4A6EA/Documents/google.com

Swift 4

extension String {


var lastPathComponent: String {
return (self as NSString).lastPathComponent
}
var pathExtension: String {
return (self as NSString).pathExtension
}
var stringByDeletingLastPathComponent: String {
return (self as NSString).deletingLastPathComponent
}
var stringByDeletingPathExtension: String {
return (self as NSString).deletingPathExtension
}
var pathComponents: [String] {
return (self as NSString).pathComponents
}
func stringByAppendingPathComponent(path: String) -> String {
let nsSt = self as NSString
return nsSt.appendingPathComponent(path)
}
func stringByAppendingPathExtension(ext: String) -> String? {
let nsSt = self as NSString
return nsSt.appendingPathExtension(ext)
}
}

如果使用 NSString路径方法(而不是 String URL 方法)是可以接受的,那么使用计算属性或返回值为 NSString的方法(而不是在 String扩展中复制所需的方法)来扩展 String会容易得多:

extension String
{
var ns: NSString { return self as NSString }
}

然后:

swiftStringPath.ns.appendingPathComponent("whateva")
swiftStringPath.ns.deletingPathExtension

我试过了,问题解决了。

以前:

let localPath = documentDirectory.URLByAppendingPathComponent(imageName)

之后:

let localPath = (documentDirectory as NSString).appendingPathComponent(imageName)