Fatal error editing core data objects - xcode

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.

Related

NSPrintOperation View Is blank

Im still new to OSX / Swift 3.1 but Im a little stumped, Ive build an epos system and its work all fine, Im just stuck with printing out the receipt.
I have build a XIB View and the corresponding swift file for it show below
class Receipt: NSView {
let currentOrder = NewOrder.instance
#IBOutlet var view: NSView!
#IBOutlet weak var facebookString: NSTextField!
#IBOutlet weak var websiteString: NSTextField!
#IBOutlet weak var totalString: NSTextField!
#IBOutlet weak var vatString: NSTextField!
#IBOutlet weak var subTotalString: NSTextField!
#IBOutlet weak var CashierName: NSTextField!
#IBOutlet weak var orderNumber: NSTextField!
#IBOutlet weak var date: NSTextField!
#IBOutlet weak var itemList: NSTextField!
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
Bundle.main.loadNibNamed("ReceiptView", owner: self, topLevelObjects: nil)
let contentFrame = NSMakeRect(0, 0, frame.size.width, frame.size.height)
self.view.frame = contentFrame
self.addSubview(self.view)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
subTotalString.stringValue = "Hello World"
view.draw(dirtyRect)
subTotalString.draw(dirtyRect)
}
}
I have added the nib name to the XIB reference and loaded a new Receipt() class and added the view to the NSPrintOperation.
let order = NewOrder.instance
let sview = Receipt()
let printer = NSPrinter(name: "EPSON TM-T88V");
let printData = NSPrintInfo()
printData.printer = printer!
let printerName = printer?.name
let docSize = NSMakeSize(CGFloat(204.0), CGFloat(200));
let res = "180x180dpi";
let speed = "Auto";
let blank = "Off";
let paperCut = "DocFeedCut";
let chashDrwr1 = "After";
let chashDrwr2 = "Off";
let buzzerControl = "Off";
let buzzerPattern = "Internal";
let buzzerRepeat = "1";
let data = TMPrintSupport.tmSetJobTicket(printData, printerName: printerName, documentSize: docSize, resolution: res, speed: speed, blank: blank, paperCut: paperCut, chashDrwr1: chashDrwr1, chashDrwr2: chashDrwr2, buzzerControl: buzzerControl, buzzerPattern: buzzerPattern, buzzerRepeat: buzzerRepeat)
let po = NSPrintOperation(view: sview.view, printInfo: printData)
// po.showsPrintPanel = false
po.canSpawnSeparateThread = true
po.cleanUp()
return po.run()
When the print view is shown it is blank and does not contain the view and is blank, I've also test printed and the print is just blank.
Any suggestions welcome, thanks

GeoTag Images from image picker swift 3

I want to get geotag location from image which is selected from image picker. I am using this code
if picker.sourceType == UIImagePickerControllerSourceType.PhotoLibrary
{
if let currentLat = pickedLat as CLLocationDegrees?
{
self.latitude = pickedLat!
self.longitude = pickedLong!
}
else
{
var library = ALAssetsLibrary()
library.enumerateGroupsWithTypes(ALAssetsGroupAll, usingBlock: { (group, stop) -> Void in
if (group != nil) {
println("Group is not nil")
println(group.valueForProperty(ALAssetsGroupPropertyName))
group.enumerateAssetsUsingBlock { (asset, index, stop) in
if asset != nil
{
if let location: CLLocation = asset.valueForProperty(ALAssetPropertyLocation) as CLLocation!
{ let lat = location.coordinate.latitude
let long = location.coordinate.longitude
self.latitude = lat
self.longitude = lat
println(lat)
println(long)
}
}
}
} else
{
println("The group is empty!")
}
})
{ (error) -> Void in
println("problem loading albums: \(error)")
}
}
}
i want to know to covert this code in swift 3 .I am new in coding with swift 3 .It will be very helpful
After hours of searching i got my ans
import UIKit
import Photos
class ViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var locationLabel: UILabel!
#IBOutlet weak var timeLabel: UILabel!
#IBOutlet weak var logi: UILabel!
#IBOutlet weak var lati: UILabel!
var lat = String()
var log = String()
var location = String()
var timeTaken = "Not Known"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func imagegeo(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var chosenImage:UIImage?
if let URL = info[UIImagePickerControllerReferenceURL] as? URL {
print("We got the URL as \(URL)")
let opts = PHFetchOptions()
opts.fetchLimit = 1
let assets = PHAsset.fetchAssets(withALAssetURLs: [URL], options: opts)
print(assets)
for assetIndex in 0..<assets.count {
let asset = assets[assetIndex]
location = String(describing: asset.location)
log = String(describing: asset.location?.coordinate.longitude)
lat = String(describing: asset.location?.coordinate.latitude)
timeTaken = (asset.creationDate?.description)!
print(log)
print(location)
print(lat)
}
}
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
chosenImage = editedImage
} else if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
chosenImage = selectedImage
}
dismiss(animated: true) {
DispatchQueue.main.async {
self.imageView.image = chosenImage
self.timeLabel.text = self.timeTaken
self.locationLabel.text = self.location
self.lati.text = self.lat
self.logi.text = self.log
}
}
}
}

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.

Display Swift array of strings on separate lines in auto resized label

I have a Swift string array populated via a FMDB SQLite result. The array prints OK to the console window. Rather than printing to the console, I would now like to have the strings in the array show on separate lines in an auto resizing label (tests_label).
Only slightly less than new to XCode, so thanks for you patience!
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tests_label: UILabel!
var databasePath = NSString()
override func viewDidLoad() {
super.viewDidLoad()
let filemgr = NSFileManager.defaultManager()
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let docsDir = dirPaths[0] as! String
databasePath = docsDir.stringByAppendingPathComponent("vmd_db.db")
let myDatabase = FMDatabase(path: databasePath as String)
if myDatabase.open(){
var arrayData:[String] = []
let query_lab_test = "SELECT lab_test FROM lab_test"
let results_lab_test:FMResultSet? = myDatabase.executeQuery(query_lab_test, withArgumentsInArray: nil)
while results_lab_test?.next() == true {
if let resultString = results_lab_test?.stringForColumn("lab_test"){
arrayData.append(resultString)
}
}
var multiLineString = join("\u{0085}", arrayData)
tests_label.text = multiLineString
tests_label.numberOfLines = 0
tests_label.lineBreakMode = NSLineBreakMode.ByWordWrapping
tests_label.sizeToFit()
//println(arrayData)
myDatabase.close()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You could create a string separated by newline character, like following:
let string = array.joinWithSeparator("\u{0085}")
Or in Swift 4:
let string = array.joined(separator: "\u{0085}")
Then just assign it to the label. For UILabel you probably should set numberOfLines to zero and resize it using sizeToFit() or some more sophisticated way.
I ended up using a TextView widget...ideal for scollable lists:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tests_scroller: UITextView!
var databasePath = NSString()
override func viewDidLoad() {
super.viewDidLoad()
let filemgr = NSFileManager.defaultManager()
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let docsDir = dirPaths[0] as! String
databasePath = docsDir.stringByAppendingPathComponent("vmd_db.db")
let myDatabase = FMDatabase(path: databasePath as String)
if myDatabase.open(){
var arrayData:[String] = []
let query_lab_test = "SELECT lab_test FROM lab_test ORDER BY lab_test ASC"
let results_lab_test:FMResultSet? = myDatabase.executeQuery(query_lab_test, withArgumentsInArray: nil)
while results_lab_test?.next() == true {
if let resultString = results_lab_test?.stringForColumn("lab_test"){
arrayData.append(resultString)
}
}
var multiLineString = join("\n", arrayData)
tests_scroller.text = multiLineString
myDatabase.close()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Swift error : class RecordSoundsViewController has no initializers

class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate{
#IBOutlet weak var recordButton: UIButton!
#IBOutlet weak var recodinginProgress: UILabel!
#IBOutlet weak var stopButton: UIButton!
var audioPlayer: AVAudioPlayer!
var recordAudio: RecordedAudio!
var audioRecorder:AVAudioRecorder
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
//hide the stop button
stopButton.hidden = true
recordButton.enabled = true
}
#IBAction func recordAudio(sender: UIButton) {
recordButton.enabled = false
stopButton.hidden = false
recodinginProgress.hidden = false
//TODO: Record the user"s voice
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
.UserDomainMask, true)[0] as String
let currentDateTime = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "ddMMyyyy-HHmmss"
let recordingName = formatter.stringFromDate(currentDateTime)+".wav"
let pathArray = [dirPath, recordingName]
let filePath = NSURL.fileURLWithPathComponents(pathArray)
println(filePath)
var session = AVAudioSession.sharedInstance()
session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
audioRecorder = AVAudioRecorder(URL: filePath, settings: nil, error: nil)
audioRecorder.delegate = self
audioRecorder.meteringEnabled = true
audioRecorder.prepareToRecord()
audioRecorder.record()
}
I don't know what I am doing wrong. My error is coming on my class.
It says
class RecordSoundsViewController has no initializers on RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate{
The error message is a bit bad from the compiler. The reason you see the error is because you have a property which does not have a default value.
In Swift all values needs to have a default value unless it's an optional.
In your case it's this property: var audioRecorder:AVAudioRecorder
In your case I would make this property an optional: var audioRecorder:AVAudioRecorder? and make sure to check for nil when using. Or to make it an implicitly unwrapped optional (if you know there's always gonna be a value): var audioRecorder:AVAudioRecorder!

Resources