Swift Barcode Scanning - ios

I am attempting add barcode scanning to my app using RSBarcodes. I'm having two issues: Not being able to update a label that displays the barcode scanned and the delegate to send the barcode to my calling view controller not working. Below is my code for the view controller that handles the scanning:
import UIKit
import AVFoundation
import RSBarcodes
class ScanViewController: RSCodeReaderViewController {
#IBOutlet weak var label1Label: UILabel!
#IBOutlet weak var label2Label: UILabel!
#IBOutlet weak var scanLabel: UIButton!
var delegate: barcodesScannedDelegate?
var codes:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
var code=""
// Do any additional setup after loading the view.
focusMarkLayer.strokeColor = UIColor.redColor().CGColor
cornersLayer.strokeColor = UIColor.yellowColor().CGColor
tapHandler = { point in
//println(point)
}
barcodesHandler = { barcodes in
for barcode in barcodes {
if !contains(self.codes, barcode.stringValue) {
self.codes.append(barcode.stringValue)
code = barcode.stringValue
}
}
println(code)
self.label1Label.text = code
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func finishedPressed(sender: UIButton) {
delegate?.barcodesScanned(self.codes)
self.dismissViewControllerAnimated(true, completion: nil)
}
#IBAction func cancelPressed(sender: UIButton) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
Just to ensure I did the delegate correctly, here is my code in Protocol.swift:
protocol selectCarrierDelegate {
func selectCarrier(carrierID: String,carrier: String)
}
protocol barcodesScannedDelegate {
func barcodesScanned(barcodes: [String])
}
And the relevant code in the controller that should receive the barcode:
class InBoundViewController: UIViewController,selectCarrierDelegate,UIAlertViewDelegate,UITableViewDelegate,UITableViewDataSource,barcodesScannedDelegate {
func barcodesScanned(barcodes: [String]) {
println("codes=\(barcodes)")
}
Anyone have any ideas why the label won't change and the delegate isn't working?

You need to update all UI in the main thread.
Try this:
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.label1Label.text = code
})
Swift 4:
DispatchQueue.main.async {
self.label1Label.text = code
}

Related

Getting API data + Optional Problems

I'm struggling to get an optional type to a Label.text. It keeps on giving me "nil" value and won't change the text.
import UIKit
class VerifyPNViewController: UIViewController {
#IBOutlet weak var VerificationMessage: UILabel!
#IBAction func backButton(_ sender: Any) {
self.view.window!.rootViewController?.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
func didSuccess(_ response: GetLoginVerificationMessage){
let Main = response.result!
DispatchQueue.main.async {
print(Main)
self.VerificationMessage?.text = Main
print(self.VerificationMessage?.text)
}
}
}
and I will get a
234443 << which is a response.result!
nil << print(self.VerificationMessage?.text)
I have no idea why this value won't go into the "self. Verification?.text" Does anyone have ideas?
Thank you.

How to receive tag pressed event using tagListView?

I'm using cocoa pod of TagListView https://github.com/ElaWorkshop/TagListView. And I need to catch the tagPressed event. I know that I should implement the delegate TagListViewDelegate, but I don't know where and how. Sorry for bad eng.
Here's my code
import UIKit
import TagListView
class MoreInfoViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBOutlet weak var tagListView: TagListView!
#IBOutlet weak var tagNameTextField: UITextField!
#IBAction func addTagButtonPressed(_ sender: UIButton) {
guard tagNameTextField.text != "" else { return }
let tagName = tagNameTextField.text!
tagNameTextField.text = ""
tagListView.addTag(tagName)
}
}
Quoting directly from the documentation,
You can implement TagListViewDelegate to receive tag pressed event:
// ...
{
// ...
tagListView.delegate = self
// ...
}
func tagPressed(title: String, tagView: TagView, sender: TagListView) {
print("Tag pressed: \(title), \(sender)")
}
Simply define your delegate and place the function within the controller and touch events should be called to this function.

IBOutlet always nil in ViewController methods but ok in IBAction & Viewdidload

I try to access some IBOutlet outside of Viewdidload and IBAction, and always get nil value. In Viewdidload and IBAction, those value are ok. Did i miss a part to declare or initialize something ?
The value are modified after viewdidload() because viewdidload is called bu the IBAction.
The View is created in storyboard, coming from a UINavigation Controller.
connection table between ViewController and UIView:
The loginServer method is called by userCredential delegate, as below:
protocol userCredentialDelegate {
func didUpdateCredential (sender:String, credential: Bool?)
}
class userCredential: NSObject {
var delegate:userCredentialDelegate?
// self.delegate = ViewController() removed
func loginServer (name: String, pwd: String) -> Bool {
dispatch_sync(dispatch_get_main_queue())
{
self.delegate?.didUpdateCredential ("login", credential: credentialStatus)
}
}
Main controller:
class ViewController: UIViewController, userCredentialDelegate {
// set the shared instance
let user = userCredential.sharedInstance
#IBOutlet weak var incorrectCredentials: UITextField!
#IBOutlet weak var username: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var logButton: UIButton!
#IBAction func logButton(sender: UIButton) {
print (incorrectCredentials?.hidden)
if logButton.titleLabel!.text == "Log Out" {
user.logoutServer ()
} else {
user.loginServer(username.text!, pwd: password.text!)
}
}
func didUpdateCredential (sender: String, credential: Bool?) {
switch sender {
case "login":
if credential! {
performSegueWithIdentifier("loginSegue", sender: self)
} else {
incorrectCredentials?.hidden = false
}
default: break
}
if let credentialResponse = credential {
loginStatus = credentialResponse
}
}
var loginStatus: Bool = false {
didSet {
if loginStatus {
incorrectCredentials?.hidden = true // always nil before, now ok
} else {
incorrectCredentials?.hidden = false // always nil before, now ok
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
user.delegate = self
incorrectCredentials.hidden = true // can work here
user.getUserInfo ()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
connection table:
You need to set the delegate to your user model in your viewDidLoad function.
Before doing user.getUserInfo() make user.delegate = self
currently you create a new Instance on the user model, that has nothing todo with you real loaded ViewController.

Swift - How do I update a label the Relative altitude change in iOS

I have managed to get this to print the Relative Altitude data to the log however what I would like to do is get it to print to a designated label.Any help would be appreciated.
import UIKit
import CoreMotion
class ViewController: UIViewController {
#IBOutlet weak var altitudeLabel: UILabel!
let altimeter = CMAltimeter()
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 start(sender: AnyObject) {
if CMAltimeter.isRelativeAltitudeAvailable() {
altimeter.startRelativeAltitudeUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { data, error in
if (error == nil) {
println("relative Altitude: \(data.relativeAltitude)")
println("Pressure: \(data.pressure)")
}
})
}
}
}
You can use the following line to assign a float value with 2 decimal places to your UILabel outlet:
self.altitudeLabel.text = String(format: "%0.2f", data.relativeAltitude)
I ended up using this and it will due for now:
var myIntValue:Int = Int(data.relativeAltitude)
println ("My value is \(myIntValue)")
self.altitudeLabel.text = ("\(myIntValue) M")

Swift If Statement Not Working with UILabel

My if statement is not displaying what I want it to. Can anyone help? I want to display some text in a UILabel that will be decided from weather the random number is below or above 50.
Here is the code. The IF Statement is at the end.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var pianoSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("two_tone_nav", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
audioPlayer = AVAudioPlayer(contentsOfURL: pianoSound, error: nil)
audioPlayer.prepareToPlay()
// 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.
}
#IBOutlet weak var Number: UILabel!
#IBOutlet weak var BA50: UILabel!
#IBAction func Generate(sender: AnyObject) {
audioPlayer.play()
var Generate = Int(arc4random_uniform(100))
Number.text = String(Generate)
func AboveBelow50(){
if Generate>=50 {
self.BA50.text = "No"
}
else {
self.BA50.text = "Yes"
}
}
}
}
Put your function:
func AboveBelow50(Generate: Int){
if Generate>=50 {
self.BA50.text = "No"
} else {
self.BA50.text = "Yes"
}
Out side your IBAction, and change it this way.
And call inside your IBAction:
var Generate = Int(arc4random_uniform(100))
AboveBelow50(Generate)

Resources