the programming language español descargar apple ios swift swift2

ios - programming - stringByAppendingPathComponent no está disponible



swift wikipedia (10)

En su lugar, puede usar URLByAppendingPathComponent (). Tenga en cuenta que debe recortar la cadena de ruta para eliminar el prefijo "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 }

Mi aplicación comparte una foto en Instagram, para hacer esto primero la guarda en un directorio temporal:

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

Estaba trabajando en Swift 1.2 , pero no funciona en Swift 2.0 .

El mensaje de error dado es:

stringByAppendingPathComponent no está disponible: use URLByAppendingPathComponent en NSURL en su lugar.


Está funcionando para NSString por lo que puede usarlo así:

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

Ahora puede usar esta extensión que convertirá su String a NSString primero y luego realizará la operación.

Y tu código será:

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

Aquí hay algunos otros métodos de uso:

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) } }

Referencia desde HERE .

Para 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) } }


Haz lo siguiente:

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


Para swift 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 }


Parece que el método stringByAppendingPathComponent se elimina en Swift 2.0, por lo que lo que sugiere el mensaje de error es usar:

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

Actualizar:

URLByAppendingPathComponent() ha sido reemplazado por appendingPathComponent() así que en su lugar:

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


Si es aceptable usar métodos de ruta NSString (en lugar de métodos URL de String ), es mucho más fácil extender String con una propiedad calculada o un método que devuelva su valor como NSString (en lugar de duplicar los métodos deseados en String extensión String ):

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

y entonces:

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


Simplemente envuelva su cadena como NSString .

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


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) } }


para Swift 3 :

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

o mejor cree esta extensión:

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

uso:

let writePath = NSTemporaryDirectory().appendingPathComponent(directoryname)


Solución Swift 3:

Aquí hay una función para obtener la ruta del directorio de documentos

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

Cómo utilizar:

getDocumentsDirectory.appendingPathComponent("google.com")

Resultado:

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