The code below is giving me the error " 'AnyObject' is not convertible to 'String' " at the line where I put my "if let" statement to unwrap the optional productData pulled from Parse. I'm just trying to pull a String from an object in Parse. I've checked everywhere and all the standard answers/solutions aren't working. Any thoughts?
Most of this code is taken straight from the Parse iOS docs Here
import Foundation
import Parse
func getDataFromParse () {
var productDataFromParse = PFQuery(className:"Product")
productDataFromParse.getObjectInBackgroundWithId("uyeXHufDgq") {
(productData: PFObject?, error: NSError?) -> Void in
if error == nil && productData != nil {
if let productTitle = productData["productTitle"] as! String {
self.productTitle = productTitle
}
} else {
println(error)
}
}
}
productData: PFObject? object is an optional itself. You can't subscript over it yet, because it needs to be unwrapped before. You can replace the productData != nil check with optional chaining.
In Swift 1.2 you can do that and your error checking in the same statement:
if let productTitle = productData?["productTitle"] as? String
where error == nil {
self.productTitle = productTitle
}
Note the additional ? between the productData and the square brackets.
Related
There is crash while the casting the jsonstring to object using objectMapper framework in the following part of the code but the way I have implemented is correct I guess.
Could not cast value of type '__NSCFData' (0x39490110) to 'NSString' (0x394990ac)
Here is the code:
static func saveUserRefererInfo(userRefInfo : UserRefererInfo?)
{
if userRefInfo != nil {
let jsonText = Mapper().toJSONString(userRefInfo!, prettyPrint: true)!
userDefaults.set(jsonText, forKey: SharedPreferenceHelper.USER_REFERER_INFO)
} else {
userDefaults.set(nil, forKey: SharedPreferenceHelper.USER_REFERER_INFO)
}
}
static func getUserRefererInfo() -> UserRefererInfo?
{
let userRefInfo = userDefaults.value(forKey: SharedPreferenceHelper.USER_REFERER_INFO)
if userRefInfo != nil {
return Mapper<UserRefererInfo>().map(JSONString: userRefInfo! as! String)
}
return nil
}
The crash is happening in this line of the code:
return Mapper<UserRefererInfo>().map(JSONString: userRefInfo! as! String)
The error is pretty clear: The type of userRefInfo is (NS)Data.
I don't know how userRefInfo is processed further but this is the usual way to get Data from UserDefaults.
if let userRefInfo = userDefaults.data(forKey: SharedPreferenceHelper.USER_REFERER_INFO)
return Mapper<UserRefererInfo>().map(JSONString: userRefInfo)
}
Never value(forKey: and never if foo != nil { ... foo! }
Consider that ObjectMapper became obsolete in favor of Codable in Swift 4+
While I try to pass it to temporary variables it doesn't seem to happen.
Although there are no errors while building the app, once I try to enter a value for "rateOfPaddy", it fails, citing "fatal error: unexpectedly found nil while unwrapping an Optional value"
Please let me know if I'm doing anything wrong, either related to Swift or Eureka?
form +++ Section()
<<< DateTimeRow() {
$0.tag = "RecordDateTag"
$0.title = "Date"
$0.value = NSDate()
}.cellSetup { cell, row in
cell.textLabel?.textColor = UIColor.blackColor()
}.onCellHighlight { _ in
if let dateInput = formInput["RecordDateTag"] as? String {
self.dateInputValue = dateInput
}
}.onCellUnHighlight { _ in
if let dateInput = formInput["RecordDateTag"] as? String {
self.dateInputValue = dateInput
}
}
I used .onChange callback to check and pass the information to local variables, which was of no use. .onCellHighlight and .onCellUnHighlight combination didn't do the trick either!!
Try calling values function as documented here
You can create a method like below and call it from onChange callbacks
func updateValues() {
let allFormData = formInput.values()
if let dateInput = allFormData["RecordDateTag"] as? String {
self.dateInputValue = dateInput
}
}
The error "fatal error: unexpectedly found nil while unwrapping an Optional value" means that you are trying to unwrap an optional that has nil as a value.
Verify that every formInput[KEY] has a value of the type you expect before forcing the unwrap with the as!
You could benefit from the Optional Binding
if let value = formInput["Some"] as? Int
{
//Value exist and is an Int
}
else
{
print("Not an Int")
}
For More references:
Swift Type Casting
Swift Optionals
I am having trouble translating Parse documentation into new Swift requirements. I want to update an object but I keep getting back an error that I can't assign a value of type Bool to type AnyObject? I know the column for "viewed" is Bool. Here is my code.
var query = PFQuery(className:"Post")
query.getObjectInBackgroundWithId(self.threadImageIds[objectIDkey]) {
(object, error) -> Void in
if error != nil {
println(error)
} else {
object["viewed"] = true // this is where error is occuring
object!.saveInBackground()
}
}
Thanks in advance.
After a lot of searching and trying to unwrap optionals the way Swift wants me to, the following worked
query.getObjectInBackgroundWithId(self.threadImageIds[objectIDkey]) {
(object, error) -> Void in
if error != nil {
println(error)
} else {
if let object = object {
object["viewed"] = true as Bool
}
object!.saveInBackground()
}
}
You can't store a BOOL there, you need to use a NSNumber of a BOOL. Try true as NSNumber
It is not working because you're trying to apply the subscript to the optional and not to the object, so try unwrapping
object!["viewed"] = true
I want to display the highest scores of a GKPlayer with a GKLeaderboard in Swift.
func login() {
if (GKLocalPlayer.localPlayer().authenticated) {
var leaderboardRequest: GKLeaderboard!
leaderboardRequest.identifier = "Best_Score"
// Error: fatal error: unexpectedly found nil while unwrapping an Optional value
func loadLeaderboardsWithCompletionHandler(completionHandler: (([AnyObject]!,
NSError!) -> Void)!) {
var localPlayerScore: GKScore = leaderboardRequest.localPlayerScore
}
}
}
Though, func loadLeaderboardsWithCompletionHandler returns this error message: fatal error: unexpectedly found nil while unwrapping an Optional value because I'm forcing unwrapping an Optional that contains nil.
Where's the error with my code?
You're declaring GKLeaderboard, but not initializing it. Note also that loadLeaderboardWithCompletionHandler is a class function of GKLeaderBoard. Do this instead:
if (GKLocalPlayer.localPlayer().authenticated) {
GKLeaderboard.loadLeaderboardsWithCompletionHandler { objects, error in
if let e = error {
println(e)
} else {
if let leaderboards = objects as? [GKLeaderboard] {
for leaderboard in leaderboards {
if let localPlayerScore = leaderboard.localPlayerScore {
println(localPlayerScore)
}
}
}
}
}
}
As a sidenote, it's not safe to use implicitly unwrapped optionals, i.e., anything declared with a !. Take for example your program here: you can compile it and have to dig through your code to find where the runtime error actually occurred. If you would have declared var leaderBoardRequest: GKLeaderBoard?, you would have been able to identify the source of your problem immediately without having to compile and run.
I'm using CLGeocoder for reverse geolocation and get array of CLPlacemark. When I use GPS outside the US (i.e. -27,127) and then access placemark.postalCode, the app crashes with:
"fatal error: unexpectedly found nil while unwrapping an Optional value".
It seems, that placemark.postalCode is nil where no postal code is available. But postalCode return type in Swift is String!:
var postalCode: String! { get } // zip code, eg. 95014
So I can't even test is for nil, because the crash is caused by the getter of postalCode.
Any ideas how to prevent this crash? Thank you!
Being an optional, even if implicitly unwrapped, you can check it for nil:
if placemark.postalCode != nil {
}
and the app won't crash because of that :)
To prove it, just try this code in a playground, where 2 implicitly unwrapped properties (a computed and a stored) are checked for nil:
struct Test {
var nilComputed: String! { return nil }
var nilStored: String! = nil
}
var test = Test()
if test.nilComputed != nil {
print("It's not nil")
} else {
print("It's nil")
}
if test.nilStored != nil {
print("It's not nil")
} else {
print("It's nil")
}