Mon application partage la photo sur Instagram. Pour ce faire, elle l'enregistre d'abord dans un répertoire temporaire:
let writePath = NSTemporaryDirectory().stringByAppendingPathComponent("instagram.igo")
Il travaillait sur Swift 1.2
, mais ne fonctionne pas sur Swift 2.0
.
Le message d'erreur donné est:
stringByAppendingPathComponent n'est pas disponible: utilisez plutôt URLByAppendingPathComponent sur NSURL.
Il semble que la méthode stringByAppendingPathComponent
soit supprimée dans Swift 2.0. Le message d'erreur suggère donc d'utiliser:
let writePath = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("instagram.igo")
Mise à jour:
URLByAppendingPathComponent()
a été remplacé par appendingPathComponent()
alors faites plutôt:
let writePath = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("instagram.igo")
Cela fonctionne pour NSString
afin que vous puissiez l'utiliser comme ceci:
extension String {
func stringByAppendingPathComponent(path: String) -> String {
let nsSt = self as NSString
return nsSt.stringByAppendingPathComponent(path)
}
}
Vous pouvez maintenant utiliser cette extension qui convertira d’abord votre String
en NSString
, puis effectuera l’opération.
Et votre code sera:
let writePath = NSTemporaryDirectory().stringByAppendingPathComponent("instagram.igo")
Voici d'autres méthodes d'utilisation:
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)
}
}
Référence de ICI .
Pour 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)
}
}
Enroulez simplement votre chaîne sous la forme NSString
.
let writePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("instagram.igo")
pour Swift:
let writePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(directoryname).path
ou mieux créer cette extension:
extension String {
func appendingPathComponent(_ string: String) -> String {
return URL(fileURLWithPath: self).appendingPathComponent(string).path
}
}
usage:
let writePath = NSTemporaryDirectory().appendingPathComponent(directoryname)
Swift 3 Solution:
Voici une fonction pour obtenir le chemin du répertoire de documents
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in:.userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
Comment utiliser:
getDocumentsDirectory.appendingPathComponent("google.com")
Résultat:
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
Pour 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
}
Vous pouvez utiliser URLByAppendingPathComponent () à la place. Veuillez noter que vous devez couper la chaîne du chemin pour supprimer le préfixe "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
}
Faites ce qui suit:
(("\(fileName)" as NSString).lastPathComponent as NSString).stringByDeletingPathExtension