I entered my samplePlist.plist in the project folder and I'm trying to save the data on this .....
var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) //Get Path of Documents Directory
var documentsDirectory:AnyObject = paths[0]
var path = documentsDirectory.stringByAppendingPathComponent("samplePlist.plist")
var fileManager = NSFileManager.defaultManager()
var fileExists:Bool = fileManager.fileExistsAtPath(path)
var data : NSMutableDictionary?
//Check if plist file exists at path specified
if fileExists == false {
//File does not exists
data = NSMutableDictionary () //Create data dictionary for storing in plist
} else {
//File exists – retrieve data from plist inside data dictionary
data = NSMutableDictionary(contentsOfFile: path)
}
data?.setValue("\(countButton)", forKey: "NumeroButton")
data?.writeToFile(path, atomically: true) //Write data to file permanently
and i Read to the plist
//Get path of Documents directory
var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var documentsDirectory:AnyObject = paths[0]
var path = documentsDirectory.stringByAppendingPathComponent("samplePlist.plist")
//Retrieve contents from file at specified path
var data = NSMutableDictionary(contentsOfFile: path!)
println(path)
my problem is that ,if I try to start it on my iphone ,I do not upload the file to the My Documents folder on startup of the Application
/var/mobile/Containers/Data/Application/9CCDBD0B-FA29-4C9E-910E-9AD5F5B11E5A/Documents/samplePlist.plist
fatal error: unexpectedly found nil while unwrapping an Optional value
Related
I have string array of file names, which looks like this
["xBGEx.jpg", "OgJuM.jpg"]
This is images, which saved to documents directory. I try to create array of UIImages by appending full path in for look and then appending to array.
In my appDelegate I have code in didFinishLaunchingWithOptions it looks like
var paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var documentsDirectory = paths[0] as? String
self.documentsRoot = documentsDirectory! + "/"
Then, when Im in controller, which I need I do the following
var slider = ["xBGEx.jpg", "OgJuM.jpg"]
var UIImageArray = [UIImage]()
for element in imgArray {
var path = "\(appDelegate.documentsRoot!)" + "\(element)"
var obj:UIImage = UIImage(contentsOfFile: path)!
UIImageArray.append(obj)
}
imageArray = UIImageArray
but when I build I have nil error in the moment of appending
What am I doing wrong ?
Seems like the path doesn't lead to an image file.
You should check if the file you found a path for really is an image and not force the cast with !
for element in imgArray {
var path = "\(appDelegate.documentsRoot!)" + "\(element)"
if let obj = UIImage(contentsOfFile: path) {
UIImageArray.append(obj)
}
}
On another note PLEASE don't name your variables with a capital letter
uiImageArray would be much better.
I have a program, where the user "creates" an image, and then the program takes a screenshot of the screen. I would then like to save this screenshot to a database, prefferebly nsuserdefaults, since I am accessing it later in a table view. Any other suggestions on how to approach this, are more than welcome :)
The code is like this
let screenshot = getScreenshot() // saves the screenshot
var imagePaths = [String]()
// get the array of previous screenshots
if let _ = NSUserDefaults.standardUserDefaults().objectForKey(theKey)
{
imagePaths = NSUserDefaults.standardDefaults().objectForKey(theKey) as! [String]
}
// then I want to get a path to the image something like
let imagePath = screenshot.getPath() // although this is not a valid method, this is basically what I want
// add the imagePath
imagePaths.append(imagePath)
// finally I save the image
NSUserDefaults.standardUserDefaults().setObject(imagePaths, forKey: theKey)
You can create directory in Documents and save there screenshots as usual files. Filename can be generated from date and time for uniqueness.
func saveImage(imageData: NSData)
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy hh.mm.ss"
let filename = "\(dateFormatter.stringFromDate(NSDate())).png"
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
let imagesDirectory = documentsDirectory.stringByAppendingPathComponent("Images")
let filePath = imagesDirectory.stringByAppendingPathComponent(filename)
if !NSFileManager.defaultManager().fileExistsAtPath(imagesDirectory)
{
var error: NSError?
NSFileManager.defaultManager().createDirectoryAtPath(imagesDirectory, withIntermediateDirectories: false, attributes: nil, error: &error)
if error != nil
{
println("\(error!.localizedDescription)")
return
}
}
imageData.writeToFile(filePath, atomically: true)
}
func getImagesPaths() -> [String]?
{
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
let imagesDirectory = documentsDirectory.stringByAppendingPathComponent("Images")
if let filenames = NSFileManager.defaultManager().contentsOfDirectoryAtPath(imagesDirectory, error: nil)
{
let imagePaths = filenames.map{"\(imagesDirectory)/\($0)"}.filter(){$0.pathExtension == "png"}
return imagePaths.count > 0 ? imagePaths : nil
}
return nil
}
To save image simply use saveImage(data). To get images paths use getImagesPaths().
If you need array of UIImage, you can get it by follow way:
var images : [UIImage] = [ ]
if let imagePaths = getImagesPaths()
{
for path in imagePaths
{
if let image = UIImage(contentsOfFile: path)
{
images.append(image)
}
}
}
I want to check whether my File is exist with just prefix of file name in SWIFT.
E.g
My file name is like Companies_12344
So after _ values are dynamic but "Companies_" is static.
How can i do that?
I have already done split filename code below
How can i check through NSFileManager for is exist file name with "Companies_"
My code below For split
func splitFilename(str: String) -> (name: String, ext: String)? {
if let rDotIdx = find(reverse(str), "_")
{
let dotIdx = advance(str.endIndex, -rDotIdx)
let fname = str[str.startIndex..<advance(dotIdx, -1)]
println("splitFilename >> Split File Name >>\(fname)")
}
return nil
}
I think this code you need:
let str = "Companies_12344"
if str.hasPrefix("Companies") {
println("Yes, this one has 'Companies' as a prefix")
let compos = str.componentsSeparatedByString("_")
if let file = compos.first {
println("There was a code after the prefix: \(file)")
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
var yourPath = paths.stringByAppendingPathComponent("\(file)_")
var checkValidation = NSFileManager.defaultManager()
if (checkValidation.fileExistsAtPath(yourPath))
{
println("FILE AVAILABLE");
}
else
{
println("FILE NOT AVAILABLE");
}
}
}
Hello I have a NSString that contains Plist data. I need to convert it to NSDictionary. I have found ways to do it with a file but I want to do it directly in memory. How can I do this with swift? thank you for the help.
var plist : NSMutableDictionary
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("info.plist")
plist = NSMutableDictionary(contentsOfFile: readPath)!
println(plist)
}
}
}
After alot a alot of gooling and playing with it I came across
var data = stringWithPlistInside.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
var error : NSError?
var dic: AnyObject! = NSPropertyListSerialization.propertyListWithData(data!, options: 0, format: nil, error: &error)
Just in case anyone else happens to be stuck in my situation.
in my progect i add a item on plist in this mode
//Get path of Documents directory
var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var documentsDirectory:AnyObject = paths[0]
var path = documentsDirectory.stringByAppendingPathComponent("samplePlist.plist")
var fileManager = NSFileManager.defaultManager()
var fileExists:Bool = fileManager.fileExistsAtPath(path)
var data : NSMutableDictionary?
//Check if plist file exists at path specified
if fileExists == false {
//File does not exists
data = NSMutableDictionary () //Create data dictionary for storing in plist
} else {
//File exists – retrieve data from plist inside data dictionary
data = NSMutableDictionary(contentsOfFile: path)
}
data?.setValue("hi", forKey: "NameButton")
my plist is this
<dict>
<key>NameButton</key>
<string>1</string>
</dict>
</plist>
and if i want remove NameButton from my plist ?