Can not create UIImage and append it to array - swift

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.

Related

How to get some data out of an array in swift?

Here is my problem: I have an plist file, which have a simple strut:
root object is an array, and there are 2 sections in the array, each of them are dictionary including 2 pair key-value data:
and I'm going to create a tableView to show the datas, but I can't get the content out of the array :
here is how i declared my dataArray:
var plistArray = [AnyObject]()
can some one help me?
You need to properly cast at each level:
if let innerArray = plistArray[0] as? [AnyObject] {
if let dataDic = innerArray[indexPath.row] as? [String:String] {
if let imageName = dataDic["Pic"] {
cell?.imageView?.image = UIImage(named: imageName)
}
}
}
But why are you using AnyObject when you know what the plist contains? Use proper types. You know it's an array of arrays of dictionaries with String keys and String values.
var plistArray = [[[String:String]]]()
Then all you need is:
if let imageName = plistArray[0][indexPath.row]["Pic"] {
cell?.imageView?.image = UIImage(named: imageName)
}

Append to array in swift - has no member append?

What am I doing wrong in this code?
and why do I get the error ?
"Value of type 'NSMutableArray' has no member 'append'"
static func saveUserData()
{
let item:NSDictionary = ["TIME":"12:00","LOCATION":"here"]
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
let filePath = documentsDirectory + "/datafile.dat"
var readArray:NSMutableArray? = NSMutableArray(contentsOfFile: filePath)
if var array = readArray {
print("loaded array - appending..." )
// PROBLEM IS HERE
var damnArray:NSMutableArray = array
damnArray.append(item)
} else {
//
}
}
Because you are using NSMutableArray, you need to use addObject
damnArray.addObject(item)
append is used with swift array like this way
var arr = [Int]()
arr.append(5)
For more detail about swift array check this apple documentation or this tutorial.
Your had declared dammArray as NSMutableArray. So there is no method append is available. Append is available in swift array object.
var damnArray:NSMutableArray
damnArray.addObject(item)
or
var damnArray = [NSDictionary]()
damnArray.append(item)
As per your answer and syntax this worked for me thanks, in my code which is:
#IBAction func btnSend(_ sender: UIButton)
{
//data.append(tfData.text!)
data.add(tfData.text!)
tblViewList.reloadData()
tfData.resignFirstResponder()
}

Swift Save images (screenshots) to nsuserdefaults

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

How to point a Json array to a local image?

I'm new at this so sorry if this is basic but I'm trying to use an array in a json file and have it point to an image in my asset library but I'm running into problems. Its written as:
[
{
"image":"shrew",
},
]
Is it wrong to write it as a string? Do I need to have specific code to translate the string into my image names?
Thanks for any help you can offer!
Edit:
The error I'm getting is on line
TrackPic.image = image
"Use of unresolved identifier 'TrackPic'"
class QuizModel: NSObject {
func getQuestions() -> [Question] {
// Array of question objects
var questions:[Question] = [Question]()
// Get Json array of dictionaries
let jsonObjects:[NSDictionary] = self.getLocalJsonFile()
// Loop through each dictionary and assign values to our question objs
var index:Int
for index = 0; index < jsonObjects.count; index++ {
// Current JSON dict
let jsonDictionary:NSDictionary = jsonObjects[index]
// Create a question obj
var q:Question = Question()
let imageName = jsonDictionary["image"] as! String
let image = UIImage(named: imageName)
TrackPic.image = image
// Assign the values of each key value pair to the question object
q.image = jsonDictionary["image"] as! String
q.questionText = jsonDictionary["question"] as! String
q.answers = jsonDictionary["answers"] as! [String]
q.correctAnswerIndex = jsonDictionary["correctIndex"] as! Int
q.module = jsonDictionary["module"] as! Int
q.lesson = jsonDictionary["lesson"] as! Int
q.feedback = jsonDictionary["feedback"] as! String
// Add the question to the question array
questions.append(q)
}
// Return list of question objects
return questions
}
you first need to get the image name from the json like you did
let imageName = jsonDictionary["image"] as! String
(If you want to be certain that you are parsing your JSON correctly, be sure to write the imageName to the console)
Then you need to initialise a UIImage with UIImage(named: String) with you image name from json so
let image = UIImage(named : imageName)
Then you have your image, and you can put this on an UIImageView.
I suppose in your case, this would be
q.image = image
IF q is a UIImageView

Swift Save/Reload data to plist

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