mountedVolumeURLsIncludingResourceValuesForKeys error - cocoa

So i was trying to get some information about my usb devices and all of them seem to have the same output for NSURLVolumeIsRemovableKey, NSURLVolumeIsEjectableKey, and NSURLVolumeIsReadOnlyKey. I do see the different key names and correct volume sizes, is there an issue with my code? or is this something else?
var filemanager: NSFileManager = NSFileManager()
var keys: NSArray = [NSURLVolumeNameKey, NSURLVolumeIsRemovableKey,NSURLVolumeIsEjectableKey,NSURLVolumeIsReadOnlyKey,NSURLVolumeMaximumFileSizeKey]
var url = filemanager.mountedVolumeURLsIncludingResourceValuesForKeys(keys, options: nil)!
for items in url
{
var a: AnyObject?
var b: AnyObject?
var c: AnyObject?
var d: AnyObject?
var e: AnyObject?
var err: NSError?
items.getPromisedItemResourceValue(&a, forKey: NSURLVolumeNameKey, error: &err)
items.getPromisedItemResourceValue(&b, forKey: NSURLVolumeIsRemovableKey, error: &err)
items.getPromisedItemResourceValue(&c, forKey: NSURLVolumeIsEjectableKey, error: &err)
items.getPromisedItemResourceValue(&d, forKey: NSURLVolumeIsReadOnlyKey, error: &err)
items.getPromisedItemResourceValue(&e, forKey: NSURLVolumeMaximumFileSizeKey, error: &err)
println("itemname: \(items)")
println(a!)
println(b!)
println(c!)
println(d!)
println(e)
}

Related

how to get UrlPath and name of images in the array in swift 3?

I have an array of images that selected from gallery in the swift 3
I used method below for get these images url path and names but It doesn't work for me
I read this
How to get the image or movie path from the photo Library in swift
but the problem is that I stored images in the array and want to get url path and names from this array
here is the codes
let imageURL = init[UIImagePickerControllerReferenceURL] as NSURL
let imageName = imageURL.path!.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let localPath = documentDirectory.stringByAppendingPathComponent(imageName)
let image = info[UIImagePickerControllerOriginalImage] as UIImage
let data = UIImagePNGRepresentation(image)
data.writeToFile(localPath, atomically: true)
let imageData = NSData(contentsOfFile: localPath)!
let photoURL = NSURL(fileURLWithPath: localPath)
let imageWithData = UIImage(data: imageData)!
For Swift 3 try this code.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let imageUrl = info[UIImagePickerControllerReferenceURL] as? NSURL
let imageName = imageUrl?.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!)
if !FileManager.default.fileExists(atPath: localPath!.path) {
do {
try UIImageJPEGRepresentation(image, 1.0)?.write(to: localPath!)
print("file saved")
}catch {
print("error saving file")
}
}
else {
print("file already exists")
}
}

Fatal error editing core data objects

I am newbie to programming. With CoreData, I am trying to create the function to edit the data in input text field to edit the data to be saved to core data. I am having fatal error:
unexpectedly found nil while unwrapping an Optional value
#IBAction func update(sender: AnyObject) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let manageContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Coursework")
do {
let results = try manageContext.executeFetchRequest(fetchRequest)
let attribute = results[0] as! NSManagedObject
detailItem?.value = modulename.text
attribute.setValue(courseworkname.text, forkey: "courseworkname")
attribute.setValue(dueDateLabel.text, forkey: "duedate")
attribute.setValue(level.text, forkey: "level")
attribute.setValue(mark.text, forkey: "mark")
attribute.setValue(modulename.text, forkey: "modulename")
attribute.setValue(notes.text, forkey: "notes")
attribute.setValue(progressbar.text, forkey: "progressbar")
attribute.setValue(reminder.text, forkey: "reminder")
attribute.setValue(value.text, forkey: "value")
try manageContext.save()
}catch let error as NSError {
}
}
Full code:
#IBOutlet weak var detailDescriptionLabel: UILabel!
#IBOutlet weak var dueDateLabel: UITextField!
#IBOutlet weak var value: UITextField!
#IBOutlet weak var courseworkname: UITextField!
#IBOutlet weak var modulename: UITextField!
#IBOutlet weak var level: UITextField!
#IBOutlet weak var mark: UITextField!
#IBOutlet weak var reminder: UITextField!
#IBOutlet weak var notes: UITextField!
#IBAction func edit(sender: AnyObject) {
modulename.userInteractionEnabled = true
modulename.enabled = true
dueDateLabel.userInteractionEnabled = true
value.userInteractionEnabled = true
modulename.userInteractionEnabled = true
level.userInteractionEnabled = true
mark.userInteractionEnabled = true
reminder.userInteractionEnabled = true
notes.userInteractionEnabled = true
//Interaction
value.enabled = true
dueDateLabel.enabled = true
courseworkname.enabled = true
modulename.enabled = true
level.enabled = true
mark.enabled = true
reminder.enabled = true
notes.enabled = true
}
#IBAction func update(sender: AnyObject) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let manageContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Coursework")
do {
let results = try manageContext.executeFetchRequest(fetchRequest)
let attribute = results[0] as! NSManagedObject
detailItem?.value = modulename.text
attribute.setValue(courseworkname.text, forKey: "courseworkname")
attribute.setValue(dueDateLabel.text, forKey: "duedate")
attribute.setValue(level.text, forKey: "level")
attribute.setValue(mark.text, forKey: "mark")
attribute.setValue(modulename.text, forKey: "modulename")
attribute.setValue(notes.text, forKey: "notes")
attribute.setValue(progressbar.text, forKey: "progressbar")
attribute.setValue(reminder.text, forKey: "reminder")
attribute.setValue(value.text, forKey: "value")
try manageContext.save()
}catch let error as NSError{
}
}
var detailItem: Coursework?
var detailItem2: Task?
{
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.courseworkname
}
if let label = self.dueDateLabel {
label.text = detail.duedate
}
if let label = self.value {
label.text = detail.value
}
if let label = self.courseworkname {
label.text = detail.courseworkname
}
if let label = self.modulename {
label.text = detail.modulename
}
if let label = self.level {
label.text = detail.level
}
if let label = self.mark {
label.text = detail.mark
}
if let label = self.reminder{
label.text = detail.reminder
}
if let label = self.notes{
label.text = detail.notes
}
}
Is it a new attribute? You have to uninstall and reinstall the app when you're changing your CoreData models.
Also just saw that you don't have an IBOutlet defined for progressbar, if you link it it should work.

Swift Error: EXE_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

I'm trying to make this posting app similar to instagram but I am getting stuck on a issue once i press my compose button. This button is suppose to post the image but instead its crashing. I'm having an error after I try to upload a caption\image with my app here:
let imageData = UIImagePNGRepresentation(imageToBeUploaded!)!
It is giving me this error:EXE_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
Please help!
#IBOutlet weak var captionTextView: UITextView!
#IBOutlet weak var previewImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
captionTextView.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func addImageTapped(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(.PhotoLibrary)!
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
self.previewImage.image = image
self.dismissViewControllerAnimated(true, completion: nil)
}
func textViewShouldEndEditing(textView: UITextView) -> Bool {
captionTextView.resignFirstResponder()
return true;
}
#IBAction func composeTapped(sender: AnyObject) {
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
let localDate = dateFormatter.stringFromDate(date)
let imageToBeUploaded = self.previewImage.image
let imageData = UIImagePNGRepresentation(imageToBeUploaded!)!
let file: PFFile = PFFile(data: imageData)!
let fileCaption: String = self.captionTextView.text
let photoToUpload = PFObject(className: "Posts")
photoToUpload["Image"] = file
photoToUpload["Caption"] = fileCaption
photoToUpload["addedBy"] = PFUser.currentUser()?.username
photoToUpload["data"] = localDate
//Get bytes size of image
/* var imageSize = Float(imageData!.length)
//Transform into Megabytes
imageSize = imageSize/(1024*1024)
print("Image size is \(imageSize)Mb")
*/
do{
try photoToUpload.save()
} catch _ {
}
print("Successfully Posted.")
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("postController")
self.presentViewController(vc! as UIViewController, animated: true, completion: nil)
}
It seems that you are unwraping an optional value without actualy checking if it is nil.
Probably the issue is from let file: PFFile = PFFile(data: imageData)!. You must check for nil before you unwrap a variable.

setResourceValue NSURLTagNamesKey error

I am getting an error when trying to set a tag color Blue to a file using setResourceValue:
var error: NSError?
let listofTags = NSWorkspace.sharedWorkspace().fileLabels
let theURL:NSURL = NSURL.fileURLWithPath("/Volumes/234567_fr.tif")!
var Tag: AnyObject = NSWorkspace.sharedWorkspace().fileLabels[4] // Tag = "Blue"
theURL.setResourceValue(Tag, forKey: NSURLTagNamesKey, error: &error)
println(error) // Error Domain=NSOSStatusErrorDomain Code=-8050 "The operation couldn’t be completed. (OSStatus error -8050.)
Any idea? Thank you for your help
Solution:
1 - The first argument for setResourceValue has to be an NSArray
2 - Shocking, but... the color name has to be the localized one!
This example fixes your error 8050 but doesn't actually set a color tag if your system language isn't English:
var error: NSError?
let theURL:NSURL = NSURL(fileURLWithPath: "/Users/me/tests/z.png")!
let tag: AnyObject = NSWorkspace.sharedWorkspace().fileLabels[4] // "Blue" tag
let arr = NSArray(object: tag)
theURL.setResourceValue(arr, forKey: NSURLTagNamesKey, error: &error)
On my system (French), this doesn't set an actual blue color label tag, only a text tag containing the word "Blue".
To set the proper color tag, you have to give the localized color name literally:
var error: NSError?
let theURL:NSURL = NSURL(fileURLWithPath: "/Users/me/tests/z.png")!
let arr = NSArray(object: "Bleu") // "Blue" translated to French
theURL.setResourceValue(arr, forKey: NSURLTagNamesKey, error: &error)

Xcode 6: Operand of Postfix "!" should have optional type

Running Xcode 6 Beta 7,
I'm trying to unwrap a dictionary called detail, with a key categories which is an array of category dictionaries. Each category is of type [String : AnyObject]
var category: [String: AnyObject] = detail!["categories"]![categoryIndex] as [String: AnyObject]
I get the error
Operand of Postfix "!" should have optional type, type is '(String, AnyObject)'
If I remove the exclamation point "!" as the compiler suggested
var category: [String: AnyObject] = detail!["categories"][categoryIndex] as [String: AnyObject]
I get the error
(String, AnyObject) does not have the member named `subscript`
Help!
Here is my detail declaration
var detail: [String : AnyObject]?
The problem seems to be that the compiler can't figure out how to cast the various AnyObjects when accessing them like that. You can get around it with some creative inline casting:
var category: [String: AnyObject]? = ((detail?["categories"] as AnyObject?) as? [[String: AnyObject]])?[categoryIndex]
It would nicer to separate those steps out though:
var categoriesObj: AnyObject? = detail?["categories"]
var categories: [[String: AnyObject]]? = categoriesObj as? [[String: AnyObject]]
var category: [String: AnyObject]? = categories?[categoryIndex]
Note: I had to change category to an [String: AnyObject]?

Resources