如何将代码目标c转换为Swift以保存图像? [英] How to convert code objective c to Swift to save image?
问题描述
我在其他帖子中也看到了这段代码,用于保存图片:
I have seen this code in other post, for save pictures:
// Create path.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];
// Save image.
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
我正在尝试转换为swift以使用avfoundatioin保存照片,但是我不知道在这里键入NSDocumentDirectory和NSUserDomainMask 如何转换呢?
An d I'm trying convert to swift for save a picture take with avfoundatioin but I dont know type NSDocumentDirectory and NSUserDomainMask here How can convert this??
谢谢!
推荐答案
如下:
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
if paths.count > 0 {
if let dirPath = paths[0] as? String {
let readPath = dirPath.stringByAppendingPathComponent("Image.png")
let image = UIImage(named: readPath)
let writePath = dirPath.stringByAppendingPathComponent("Image2.png")
UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true)
}
}
}
路径"是AnyObject [],因此您必须检查其元素是否可以转换为String.
"paths" is an AnyObject[], so you have to check that its elements can be converted to String.
自然地,您实际上不会使用"NSDocumentDirectory"作为名称,为了清楚起见,我只是这么做了.
Naturally, you wouldn't actually use "NSDocumentDirectory" as the name, I just did it for clarity.
更新了Xcode 7.2
NSSearchPathForDirectoriesInDomains
现在返回[String]
而不是[AnyObject]?
,因此请使用
NSSearchPathForDirectoriesInDomains
now returns [String]
rather than [AnyObject]?
so use
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first {
// ...
}
.stringByAppendingPathComponent
也被弃用的事实在此答案中 ...
The fact that .stringByAppendingPathComponent
is also deprecated is dealt with in this answer...
这篇关于如何将代码目标c转换为Swift以保存图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!