how to get key of selected value from nsdictionary - ios

I am using NSDictionary to get data from json and then i added the value from NSDictionary to UITableView.When user is selected one of the table cell it will send back the value.The point is how to get the key of selected value from table cell in NSDictionary in Swift?
import UIKit
class ViewController: UIViewController {
var myFruits = ["0_22":"Sunkist","34_22":"Pine Apple","45_22":"Grape","1_123":"Apple"]
override func viewDidLoad() {
super.viewDidLoad()
// If my selected key is "Sunkist, what do i need to to get its value (0_22)"
// Any Code Help?
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

This code will work fine.
var myFruits = ["0_22":"Sunkist","34_22":"Pine Apple","45_22":"Grape","1_123":"Apple"]
var dic:NSDictionary = NSDictionary(dictionary:myFruits)
println(dic.allKeysForObject("Sunkist"))

Thanks for #Martin R who give me that answer.I got this now with that code
let keys = (myFruits as NSDictionary).allKeysForObject("Sunkist")
println(String(keys[0] as! NSString))
Output is
0_22

Related

Custom Address Search iOS mapkit

Learning swift 2/ Xcode 7 and creating a app iOS 9 where I can enter a custom address. I have mapkit working and can search regular address. I have my current location working. Instead of entering an address: "Number,Street, city, zip code", I want the user to enter: PR33.1 for example, and that would show the user that location. I have the long and lats for the custom address's, I've read many things on geocoding and annotations but nothing that would let me accomplish what I need. Can this be done? jSon file maybe.. I'm really new at this...
thanks
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
let arbitraryString: [String:String] =
["161 RL2": "23908709138882,-106.7433588579297",
"40.9 RL112":"32.393144,-106.727762"]
#IBAction func enterButtonTapped(sender: AnyObject) {
if let textField = arbitraryString["161 RL2"] {
print(" \(textField).")
} else {
print("That is not in the dictionary.")
}
}
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.
}
}

I am getting errors such as " braced block of statements is an unused closure" and expected expression

This is my first time doing a simple project in swift and these errors are bugging me for last couple of hours. I have this code below and even though i have curly braces around and statements inside the if/else i still get that errors. Any help would be greatly appreciated guys.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var `switch`: UISwitch!
#IBOutlet var Answer: UILabel!
#IBOutlet var tempInput: UITextField!
//aqnswer value
#IBAction func switchPressed(sender: AnyObject)
{
if switch.on {
self.Answer.text = "cel to fah"
}
else {
self.Answer.text = "fah to cel"
}
}
//textfield value
#IBAction func calculate(sender: AnyObject)
{
//get user input
// value = celcius
var Value:Int = tempInput.text.toInt()!
var toFah :Int = ( 32 + Value * 9 ) / 5
//to celcius
var toCel: Int = (Value-32) * 5 / 9
if switch.on {
self.Answer.text = toFah.description
}
else {
self.Answer.text = toCel.description
}
// println(fah)
// Answer.text = fah.description
}
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.
}
}
The Swift Language Guide says:
If you need to give a constant or variable the same name as a reserved
Swift keyword, surround the keyword with back ticks (`) when using it
as a name. However, avoid using keywords as names unless you have
absolutely no choice.
In your example you have indeed a choice…
But if you really really really want to use switch as a variable name you have to wrap all occurrences of switch in back ticks.

Xcode 7 beta 2 and swift not getting along

I have an error when I typed in some code, it gave me an error. It looks perfect, but here is the code:
import UIKit
class SecondViewController: UIViewController {
#IBOutlet weak var resultLabel: UILabel!
#IBOutlet weak var tempText1: UITextField!
#IBAction func convertTemp1(sender: AnyObject) {
#let fahrenheit = (tempText1.text as NSString).doubleValue
let celsius = (fahrenheit - 32 )/1.8
let resultText = "Celsius \(celsius)"
resultLabel.text = resultText
}
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.
}
}
It give me the following error: 'String?' is not convertable to 'NSString' On the line I put a # on. The # is not in the real code.
Note: I do not understand much computer talk so please try to speak very simply. :)
The text property of UITextField returns an optional string but your code doesn't handle optionals. Casting to NSString isn't allowed there (also not necessary to get to the doubleValue).
You need to handle the optional. For this you could force-unwrap it using !. But that can lead to crashes. It would be better to use the if let or guard let statements:
guard let fahrenheit = tempText1.text?.doubleValue else { return }
For conciseness we use optional chaining (the ?here). We could also keep this in two steps:
guard let fahrenheitString = tempText1.text else { return }
let fahrenheit = fahrenheitString.doubleValue
Both are basically equivalent.

Attempting to load Webview with PDF, receiving link from Parse

I am attempting to load a lunch menu PDF into a web view for a high school app that I am updating. Currently, it can load a PDF into the web view and display it just fine, but I want to speed up the monthly update process by having my app receive the link through Parse (Which I can update much quicker than updating the link in the app itself with Apple's 7 day review period), and then load the PDF. Currently, with what I have put together, my app will not load the PDF. Here's the entire view:
import UIKit
class AlaCarte_ViewController: UIViewController {
#IBOutlet weak var webviewAlaCarte: UIWebView!
var urlpath = String()
func loadAddressUrl(){
let requestURL = NSURL (string:urlpath)
let request = NSURLRequest(URL: requestURL!)
webviewAlaCarte.loadRequest(request)
alaCarteUpdate()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
clearPDFBackground(self.webviewAlaCarte)
}
func clearPDFBackground(webView: UIWebView) {
var view :UIView?
view = webView as UIView
while view != nil {
if NSStringFromClass(view?.dynamicType) == "UIWebPDFView" {
view?.backgroundColor = UIColor.clearColor()
}
view = view?.subviews.first as! UIView?
}
}
func alaCarteUpdate() {
var query = PFQuery(className: "AlaCarte")
query.getObjectInBackgroundWithId("rT7MpEFySU") {(AlaCarte: PFObject!, error: NSError!)-> Void in
if error == nil && AlaCarte != nil {
println(AlaCarte)
} else {
println(error)
}
let AlaCarteLink = AlaCarte["webaddress"] as! String
self.urlpath = AlaCarteLink
}
}
override func viewDidLoad() {
super.viewDidLoad()
loadAddressUrl()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
The link is stored in my Parse app as "webaddress" and does not contain end quotations. Adding them does not help. Any ideas?
It looks to me like you're not telling the web view to load the URL once it's retrieved from Parse.
Try adding the following lines after self.urlpath = AlaCarteLink in alaCarteUpdate().
let requestURL = NSURL (string:self.urlpath)
let request = NSURLRequest(URL: requestURL!)
self.webviewAlaCarte.loadRequest(request)
I think it would also be a good idea to add a function that specifically loads a url string into your web view, so you can call it from both inside alaCarteUpdate(), and loadAddressUrl(), and avoid the duplicate 3x lines. I've assumed that you're loading the URL in loadAddressURL() so that you can show a local/cached document while retrieving the latest from Parse.

Swift error about consecutive declarations on a line

I don't understand what's wrong with this code in my View Controller, the very bottom line (with the single } bracket) keeps getting two errors, one that states "Consecutive declarations on a line must be separated by ';'" and "expected declaration". When I add the semicolon where it directs me to it still says an expected declaration error....but for what? Can anyone find anything wrong with it?
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var testObject = PFObject(className:"TestObject")
testObject["foo"] = "bar"
testObject.saveInBackgroundWithTarget(nil, selector: nil)
var voteCount = PFObject(className:"VoteCount")
voteCount["votes"] = 0
voteCount["optionName"] = "Crepes"
voteCount.incrementKey("votes")
voteCount.saveEventually()
var query = PFQuery(className:"VoteCount")
query.getObjectInBackgroundWithId("e8KhneiSfw") {
(voteCount: PFObject!, error: NSError!) -> Void in
if error != nil {
NSLog("%#", error)
} else {
voteCount["votes"] = 1
voteCount.incrementKey("votes")
voteCount.saveEventually()
}
}
class Counter {
var voteCount: Int = 0
func incrementBy(amount: Int, numberOfTimes times: Int) { voteCount += amount * times
}
}
func didReceiveMemoryWarning() {
didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
There's a missing closing brace before this line:
class Counter {
Your viewDidLoad() method is not properly closed, so what happens is that the class and didReceiveMemoryWarning are defined as local to viewDidLoad.
A proper indentation usually reveals errors like that... are you properly indenting your code?
As written, class Counter and func didReceiveMemoryWarning() are inside viewDidLoad. Fix your braces.

Resources