Swift Parse - Method doesn't stop executing - ios

I have the following code which basically would query Parse class and return a result set. After returning the results, I would pass that array to a function to check if some elements are set or not.
I used print statements all over the code to try and debug, and found that query executes and within the
if error == nil
I am getting the results array to be empty. Hence when I pass that to my function below, it never gets out of it:
func emailOrUsernameIsTaken(results: [PFObject])->Int
{
/*Check if username is taken or if email is taken*/
var preferenceTaken: Int = 0
if(results[0]["email"] as! String != "" && results[0]["email"] as! String == self.userObject.email!)
{
preferenceTaken = 1
}else if(results[0]["appUsername"] as! String != "" && results[0]["appUsername"] as! String == self.userObject.username!){
preferenceTaken = 2
}
return preferenceTaken
}
and this is the code where the query is taking place:
let query = PFQuery.orQueryWithSubqueries([usernameInputCheck, emailInputCheck])
query.findObjectsInBackgroundWithBlock {
(results: [PFObject]?, error: NSError?) -> Void in
if error == nil {
print("Before")
let checkResult = self.emailOrUsernameIsTaken(results!)
print(results)
print("After")
}
}
as an output from print statements above, I get in console:
Before
Optional([])
After
Can someone help me to find out the issue. I am surprised why this is not working.

If results is empty, results[0]["email"] as! String should crash because you are force unwrapping a nil optional value. So the story you are telling is not consistent.
If the actual problem is the empty results - you would have to provide details about your queries and why you expect there to be a populated result.

Related

How to check if array contain null value and give default value swift

I have an array that's populated from a JSON response from an API server. Sometimes the values for a key in this array are Null
I am trying to take the given value and drop it into the detail text of a table cell for display.
The problem is that when I try to coerce the value into an String I get a crash, which I think is because I'm trying to coerce Null into a string.
What's the right way to do this?
ex-
my response is below type and I'm trying to fetch that array in self.imageArray variable
response = ["abc.jpg","null","xyzzy.jpg"]
self.imageArray = (self.dataArray.value(forKey: "product_image") as? [String])!
but at second iteration it gets crashed coz second value is null.
In your case only (Solution according to given question 'response'
array) :-
response = ["abc.jpg","null","xyzzy.jpg"]
Use following code
if !response.contains("") && !response.contains("null"){
// No null or empty string now
// your code
}else{
print("Contain null or empty value")
}
You can user compatcMap in this case.
let response = ["abc.jpg", nil, "xyzzy.jpg"]
let result = response.compactMap { $0 }
print(result)
If you are sure the value will be "null" in string type then you can use the following way.
let response = ["abc.jpg", "null", "xyzzy.jpg"]
let result = response.filter { $0 != "null" }
print(result)
the combined result is
let result = response.filter { $0 != "null" }.compactMap { $0 }
print(result)
This will handle the issue for both null and nil.
response = ["abc.jpg","null","xyzzy.jpg", nil]
var result = response.filter { return ($0 != "null" && $0 != nil) }
print(result) // return option result.
It should be like
var image = ["abc.jpg", nil, "xyzz.jpg"]
image = image.filter { $0 != nil}
print(image)
You have to filter out the nil values.
if you remove specific string "null"
var image = ["abc.jpg", "null", "xyzz.jpg"]
image = image.filter { $0 != "null"}
print(image)
If you know for sure that a valid value will always contain an image type like .jpg, then you can check against that and it will remove nil values, "null" or any other random strings, including empty strings " ".
response = ["abc.jpg","null","xyzzy.jpg", nil, " "]
self.imageArray = response.filter { $0?.contains(".jpg") ?? false }

How do I fix error: Binary operator '==' cannot be applied to operands of type 'NSExpression.ExpressionType' and '_'

I am going through old code from HomeKit Catalog: Creating Homes, Pairing and Controlling Accessories, and Setting Up Triggers when I ran into an expression that says
.KeyPathExpressionType
I can't tell what the
.
in
.KeyPathExpressionType
is referring to on the left side of the
.
I find nothing when I search Google and stackoverflow for "KeyPathExpressionType". It's the same with
.ConstantValueExpressionType
I find nothing.
Each of those equality comparisons
comparison.leftExpression.expressionType == .KeyPathExpressionType
and
comparison.rightExpression.expressionType == .ConstantValueExpressionType
in the code below, generate an error message that says:
Binary operator '==' cannot be applied to operands of type 'NSExpression.ExpressionType' and '_'
extension NSPredicate {
/**
Parses the predicate and attempts to generate a characteristic-value `HomeKitConditionType`.
- returns: An optional characteristic-value tuple.
*/
private func characteristic() -> HomeKitConditionType? {
guard let predicate = self as? NSCompoundPredicate else { return nil }
guard let subpredicates = predicate.subpredicates as? [NSPredicate] else { return nil }
guard subpredicates.count == 2 else { return nil }
var characteristicPredicate: NSComparisonPredicate? = nil
var valuePredicate: NSComparisonPredicate? = nil
for subpredicate in subpredicates {
if let comparison = subpredicate as? NSComparisonPredicate, comparison.leftExpression.expressionType == .KeyPathExpressionType && comparison.rightExpression.expressionType == .ConstantValueExpressionType {
switch comparison.leftExpression.keyPath {
case HMCharacteristicKeyPath:
characteristicPredicate = comparison
case HMCharacteristicValueKeyPath:
valuePredicate = comparison
default:
break
}
}
}
if let characteristic = characteristicPredicate?.rightExpression.constantValue as? HMCharacteristic,
characteristicValue = valuePredicate?.rightExpression.constantValue as? NSCopying {
return .Characteristic(characteristic, characteristicValue)
}
return nil
}
I get the error to go away when I replace
comparison.leftExpression.expressionType == .KeyPathExpressionType
with
comparison.leftExpression.expressionType.rawValue == NSExpression.ExpressionType.keyPath.rawValue
and
comparison.rightExpression.expressionType == .ConstantValueExpressionType
with
comparison.rightExpression.expressionType.rawValue == NSExpression.ExpressionType.constantValue.rawValue
Is this correct? Can anyone tell me enlighten me on this problem?
The code is outdated Swift 2 code.
Replace .KeyPathExpressionType with .keyPath and .ConstantValueExpressionType with .constantValue
The type is NSExpression.ExpressionType, please read the documentation

If let condition true when value is missing in optional type, swift

I have parser in Objc, parser returns NSDictionary. I am using this parser in swift class. But when some value is missing on that dictionary, it shows nil value. e.g. ->
wirlessData = {
"anon" = {
};
"channel" = {
"text" = 1;
};
}
I am checking through
if let wepauthValue = wirlessData["wepauth"] {
if let value = wepauthValue["text"] {
print("\(value)") // nil
}
}
I don't how it satisfy the if let condition. Any one faced this types of problem can help me out.
Thanks,
vikash
You don't need any special code to do this, because it is what a dictionary already does. When you fetch dict[key] you know whether the dictionary contains the key, because the Optional that you get back is not nil (and it contains the value).
So, if you just want to answer the question whether the dictionary contains the key, ask:
let keyExists = dict[key] != nil
If you want the value and you know the dictionary contains the key, say:
let val = dict[key]!
But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like if let:
if let val = dict[key] {
// now val is not nil and the Optional has been unwrapped, so use it
}
I have tested it and found that value is still optional.Take a look at screenshot below to understand it better.
"anon" would be an empty dictionary. An empty dictionary is not nil, it is a dictionary. Just an empty one. A JSON parser will never, ever give nil values unless you ask for a key that is not in a dictionary. For example wirlessData ["nonexistingkey"] would give you nil.
If you be more type-strong about it with the if..let's then:
if let anonValue = wirlessData["anon"] {
if let value = anonValue["text"] as? String {
// This won't execute if value isn't converted from `anonvalue["text"]` to String specifically. This includes null been a false match too
print("\(value)") // nil
}else{
print("Value did't match string at all")
}
}
or even more specifically in your case:
if let anonValue = wirlessData["anon"] {
if let value = anonValue["text"] as? Int {
// This won't execute if value isn't converted from `anonvalue["text"]` to String specifically. This includes null been a false match too
print("\(value)") // nil
}else{
print("Value did't match int at all")
}
}
The value your parser is returning not nil, its empty so you need to check on count if inner data type is dictionary or array, I have past 1 sample here
Please use below code and correct your logic accordingly to get it work properly
let wirlessData:[String:AnyObject] = [
"anon" : [],
"channel" : [
"text" : 1
]
]
if wirlessData["anon"]?.count > 0 {
if let value = wirlessData["anon"]!["text"] {
print("\(value)") // nil
}
}
Try this below code using type check operator (is) -
if wirlessData["anon"] is [String:AnyObject]
{
let anon = wirlessData["anon"]!
print(anon)
if anon["random"] is String {
let stringValue = anon["random"]!
print("\(stringValue)")
}
else if anon["random"] is Int
{
let intValue = anon["random"]!
print("\(intValue)") // nil
}
else
{
print(" may be value did't match string & Int or nil ")
}
}

How to stop unwrapping nil values from Parse Array?

I'm having trouble getting my information back from a saved array in Parse. I'm saving the information like this.....
videoARY = [videoId, vidTitleText, vidDescription, vidIMG]
let videoSave = PFObject(className:"UserVideos")
videoSave["userObjectId"] = PFUser.currentUser()!.objectId
videoSave["vid\(saveValueLBL.text!)user"] = PFUser.currentUser()!.username
videoSave["vid\(saveValueLBL.text!)"] = videoARY
videoSave.saveInBackgroundWithBlock { (success, error ) -> Void in
if success == true
{
print("Success")
}
}
In a different viewcontroller I'm initializing an array like this....
var vid1array = [String]!()
and retrieving this way.......
let query = PFQuery(className: "UserVideos")
query.whereKey("userObjectId", equalTo: PFUser.currentUser()!.objectId!)
query.findObjectsInBackgroundWithBlock { (vid:Array?, error:NSError?) -> Void in
if !(error != nil)
{
for items in vid!
{
if let myfav1 = items["vid1"] as? NSArray
{
self.videoDescription1 = myfav1[2] as! String
self.videoTitle1 = myfav1[1] as! String
self.videoIMG1 = myfav1[3] as! String
print(self.videoDescription1)
print(self.videoIMG1)
print(self.videoTitle1)
self.vid1array.append(self.videoTitle1)
print(self.videoTitle1)
}
}
}
}
I'm printing a successful save and each element of the saved array. When I try to add one of those elements to vid1array the app crashes I get "Fatal error: unexpectedly found nil while unwrapping an Optional value". Please help.
* UPDATE *
When I print vid! I get this...
vid1 = (
"YiiqHq_kNnU",
"INFINITE \"Back\" Official MV",
"If you like this video, plz click \"LIKE\" and \"SUBSCRIBE\". INFINITE \"Back\" Official MV INFINITE Official Website : http://www.ifnt7.com INFINITE Official YouTube ...",
"https://i.ytimg.com/vi/YiiqHq_kNnU/default.jpg"
);
It's not nil but I don't see array brackets either, could that be it? I'm printing out the elements I just want to save them to my array so I can use them in my tableview later and the array is coming up nil.
* FOLLOW UP QUESTION *
Would it be advised to place this in viewWillAppear vs. I currently have it in viewDidLoad?

Code Crashes when loading an empty attribute from Cloudkit - using Swift

I am trying to get access to a record value in CloudKit, here MyPin, it has a title & subtitle attribute/field value.
However it may happen that sometimes the record value is empty(here subtitle), and it crashes at the line when I call:
var tempS: String = Annot["Subtitle"] as! String
because Annot["Subtitle"] doesn exist ...
When I do
println(Annot["Subtitle"])
it returns nil
but if I do :
if (Annot["Subtitle"] == nil) {
println("just got a nil value")
}
I never enter the if statement:
Can someone help me how to identify if the record has an empty value?
Here is my line of codes:
let container = CKContainer.defaultContainer()
let publicData = container.publicCloudDatabase
let query = CKQuery(recordType: "MyPin", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
publicData.performQuery(query, inZoneWithID: nil) { results, error in
if error == nil { // There is no error
for Annot in results {
var tempS: String = Annot["Subtitle"] as! String
}}
when you get Annot["Subtitle"] it will give you a CKRecordValue? return which has a base class of NSObjectProtocol. So in your case the field does exist but it's not a String so casting it using as! String will crash your app. Since the field exists the CKRecordValue will not be nil. However the content of that field is nil. When you print the field, it will output the .description of that field. In your case that is nil. Could you try this code instead:
if let f = Annot["Subtitle"] {
print("f = \(f) of type \(f.dynamicType)")
}
then set a breakpoint on the print line and when it stops try the following three statements in your output window:
po Annot
po f
p f
After the po Annot you should see what's in that record. Including your subtitle field. The po f is not so interesting. It will just output a memory address. The p f however will show you the actual type. If it's a string you should see something like: (__NSCFConstantString *) $R3 = 0xafdd21e0
P.S. Maybe you should call it record instead of Annot. It's a local variable so it should start with a lower case character. And it's still a record and not an Annot.
I think you are doing the right thing, but you don't see the println as it is executed in another thread (the completion part is executed asynchronously).
Try this:
if (Annot["Subtitle"] == nil) {
dispatch_async(dispatch_get_main_queue()) {
println("just got a nil value")
}
}
and see if it works!
The way I get values from cloudkit is this way. This both take care of the nil values and all other eventualities. Just note I have implemented a delegate to get my results back to the calling object asynchronously
privateDB.performQuery(query, inZoneWithID: nil) { (result, error) -> Void in
if error == nil{
for record in result{
let rec = record as! CKRecord
if let xxxVar = rec.valueForKey("fieldName") as? String{
myArray.append( xxxVar! ) //append unwrapped xxxVar to some result or whatever
}else{
//handle nil value
}
}
dispatch_async(dispatch_get_main_queue()) {
//do something with you data
self.delegate?.myResultCallBack(myArray)
return
}
}else{
dispatch_async(dispatch_get_main_queue()) {
self.delegate?.myErrorCallBack(error)
return
}
}
}
Beware, there are some changes in Swift2

Resources