Errors using PFUser.getCurrentUserInBackground() - ios

I am using Parse and PFUser in a Swift iOS app, and find myself in a case where PFUser.current() does not do exactly what I want, due to synchronisation issues.
For that reason I am trying to use: PFUser.getCurrentUserInBackground().
I got started with the code below, inspired from what can be found here: https://github.com/BoltsFramework/Bolts-ObjC.
But this document probably being a bit outdated, it does not quite work.
let userCheckTask = PFUser.getCurrentUserInBackground()
userCheckTask.continueWith {
(task: BFTask!) -> BFTask<AnyObject> in
if task.isCancelled() { // Error-1.
// the save was cancelled.
} else if task.error != nil {
// the save failed.
} else {
// the object was saved successfully.
var object = task.result() as PFObject // Error-2.
}
}
The compiler gives me two errors, this one on the line marked "Error-1"
Cannot invoke 'isCancelled' with no arguments
And this other one on the line marked "Error-2"
Expression type 'PFUser?' is ambiguous without more context
I have no idea what kind of argument 'isCancelled' is expecting.
Does anyone know how to fix those?

let userCheckTask = PFUser.getCurrentUserInBackground()
userCheckTask.continueWith {
(task: BFTask) -> BFTask<AnyObject> in
if let e = task.error {
return BFTask(error: e)
} else {
return BFTask(result: task.result)
}
}

Related

Swift: how to detect the error type using the debugger?

I'm new in iOS development, so maybe I'm thinking in the wrong way. I coded a view model with a function that calls an API, and everything works fine.
class SearchCityViewModel : ViewModelProtocol {
//OBSERVABLES
var cities = PublishSubject<[City]>()
var networkError = PublishSubject<Void>()
var generalError = PublishSubject<Void>()
init(){
print("Init SearchCityViewModel")
reinit()
}
func reinit(){}
func searchCity(stringToSearch: String){
async {
do {
if stringToSearch.count>=2 {
let cities = try await(api.getCities(cityToSearch: stringToSearch)).payload!
self.cities.onNext(cities)
}
else {
self.cities.onNext([])
}
}
catch {
self.generalError.onNext(Void())
}
}
}
Now I want to handle errors. In the catch block I want to distinguish all the errors I want to handle gracefully, and for the other ones I just want to emit a general error. To do that, firstly I need to know which error is thrown when the situation I want to handle occurs. I usually do this with the debugger. For instance, I disable the internet connection, and i create a breakpoint inside the catch block. The idea is to check which error is thrown when the internet connection is disabled, in order to create a catch block for that kind of error.
Image of the debugger
I'm struggling because with the debugger I only see that is an AFError instance, but it's not telling me nothing more that can help me to catch it.
What is wrong with my workflow? Do I really need to read all the docs every time? For each library I use?
Thank you!
Perhaps you can read the articles and then you will know how to do it better, you can use the framework -oslog instead of using print function.
debugging your logging info
I found the way. What I was missing is casting the error as NSError. In this way, with the debugger is possible to see the domain and the code of the error. In the case of Alamofire, the real error is wrapped, and it's accessible through the underlyingError attribute. Once I had the domain and the code of the error, I wrote the following code:
class SearchCityViewModel : ViewModelProtocol {
//OBSERVABLES
var cities = PublishSubject<[City]>()
var networkError = PublishSubject<Void>()
var generalError = PublishSubject<Void>()
init(){
print("Init SearchCityViewModel")
reinit()
}
func reinit(){}
func searchCity(stringToSearch: String){
async {
do {
if stringToSearch.count>=2 {
let cities = try await(api.getCities(cityToSearch: stringToSearch)).payload!
self.cities.onNext(cities)
}
else {
self.cities.onNext([])
}
}
catch {
if let afError = asAFError, let underlyingError = afError.underlyingError as NSError?, underlyingError.domain == NSURLErrorDomain, underlyingError.code == NSURLErrorNotConnectedToInternet || underlyingError.code == NSURLErrorTimedOut {
self.networkError.onNext(Void())
}
else {
self.generalError.onNext(Void())
}
}
}
}

nested asynchronous fetches with Cloudkit?

I am relatively new to coding for iOS. In the past week, I've been incorporating CloudKit into my project. One thing I want to do is get the current User recordID. Then, using that recordID, I want to fetch that user's actual record. Currently I am using the following code, which seems to work:
self.container.fetchUserRecordID() { recordID, error in
if error == nil {
self.userRecordID = recordID
DispatchQueue.main.async(execute: {
self.db.fetch(withRecordID: self.userRecordID) { record, error in
if error == nil {
self.userRecord = record
} else {
if let error = error as? CKError {
print(error)
}
}
}
})
}
else {
if let error = error as? CKError {
print(error)
}
}
}
This, however, feels messy to me. My question is two-fold: 1) In general, is it acceptable to nest asynchronous calls? 2) If not, is there a better way to accomplish what I want to do in this situation?
Thanks!

Convert any object to boolean in swift?

I am getting a dictionary as JSON response from server.From that dictionary there is a key "error" now i want to get the value of "error" key.I know that error always will be either 0 or 1.So i tried to get it as boolean but it did not work for me.Please suggest how can i convert its value to boolean.
let error=jsonResult.objectForKey("error")
//this does not work for me
if(!error)
{
//proceed ahead
}
Bool does not contain an initializer that can convert Int to Bool. So, to convert Int into Bool, you can create an extension, i.e.
extension Bool
{
init(_ intValue: Int)
{
switch intValue
{
case 0:
self.init(false)
default:
self.init(true)
}
}
}
Now you can get the value of key error using:
if let error = jsonResult["error"] as? Int, Bool(error)
{
// error is true
}
else
{
// error does not exist/ false.
}
Very Simple Way: [Updated Swift 5]
Create a function:
func getBoolFromAny(paramAny: Any)->Bool {
let result = "\(paramAny)"
return result == "1"
}
Use the function:
if let anyData = jsonResult["error"] {
if getBoolFromAny(anyData) {
// error is true
} else {
// error is false
}
}
Also, if you want one line condition, then above function can be reduced like:
if let anyData = jsonResult["error"], getBoolFromAny(anyData) {
// error is true
} else {
// error is false
}
Updated
Considering jsonResult as NSDictionary and error value is Bool. you can check it by following way.
guard let error = jsonResult.object(forKey: "error") as? Bool else{
// error key does not exist / as boolean
return
}
if !error {
// not error
}
else {
// error
}
Your error is neither 0 or 1. It is an optional object. It is nil if there was no key "error" in your JSON, otherwise it's probably an NSNumber.
It is most likely that nil means "no error" and if it's not nil and contains a zero it means "no error" and if it's not nil and contains a one it means "error" and if it's not nil and contains anything else then something is badly wrong with your json.
Try this:
let errorObject = jsonResult ["error"]
if errorObject == nil or errorObject as? NSInteger == 0
When I say "try", I mean "try". You're the responsible developer here. Check if it works as wanted with a dictionary containing no error, with a dictionary containing an error 0 or 1, and a dictionary containing for example error = "This is bad".
Check equality between error and 0 instead:
let error = jsonResult.objectForKey("error")
if error == 0 {
// proceed
}
Another Important point here is, you're using Swift and parsing the repsonse as NSDictionary. I can say that because you're using objectForKey method. Best practice would be to parse it as Swift Dictionary.
It may look like Dictionary<String:AnyObject> or [String:AnyObject]
Then you can check for the error as :
if let error = jsonResult["error"] where error == 0 {
//your code
}
Below code worked for me
if let error = jsonResult["error"] as? Int where Bool(error)
{
// error is true
print("error is true")
}
else
{
// error does not exist/ false.
print("error is false")
}

Parse iOS - How to capture the findObjects() error being thrown?

I am coding in Swift and attempting to use the findObjects() function for the Parse iOS SDK. However, I can't seem to figure out what type of error is being thrown by Parse if this function call fails. I'm a novice in Swift so that may be my issue. I attempt to call the function in a do->catch block and use the try keyword on the function call however I'm not sure what to catch. I can catch the error using the _ but I would like to grab the description from the error. Thanks!
P.S. I don't want to use the findObjectsInBackground() method.
do {
let object = try query.getFirstObject()
// do something with the object
} catch _ {
// this is where I would like to print out the error description
}
In Obj-C, which I assume will be similar, I print out the error.userInfo[#"error"] parameter of the NSError that is returned.
All you need is print(error). An example here:
func getReferenceNumberAsStringSync() -> String? {
let query = PFQuery(className: "PropertyCount")
do {
let object = try query.getFirstObject()
if let referenceNumber = object["count"] as? Int {
return String(referenceNumber)
}
} catch {
print(error)
}
return nil
}

Proper Error handling in Swift

Hey stackoverflow members,
I work really hard on getting better on Swift, now I have a trivial problem. I'm a former C# developer so Error Handling until now was try {}... catch {}... Message... Done!
Now I'm developing an App which uses some JSON APIs. It's all working, downloading JSON Data, pack them into my Objects but there is one problem. The proper Error Handling..
I have the following code to download & parse JSON:
//Download & Parse JSON
func getJSON(urlToRequest: String) -> NSDictionary {
var url: NSURL = NSURL(string: urlToRequest)
var jsonRequest: NSURLRequest = NSURLRequest(URL: url)
var jsonResponse: AutoreleasingUnsafePointer<NSURLResponse?> = nil
var error: NSError?
var dataValue: NSData = NSURLConnection.sendSynchronousRequest(jsonRequest, returningResponse: jsonResponse, error:&error)
if error.description.isEmpty {
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataValue, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
if error.description.isEmpty {
return jsonResult
}
else {
return NSDictionary(object: "Error: Something with parsing went wrong :(", forKey: "error")
}
}
else {
return NSDictionary(object: "Error: There was an error with your connection :(", forKey: "error")
}
}
The error part is just temporary, the problem is my ViewController just calls one function to get the whole data for the week (days, matchups and so on)
I call it this way:
var rWrapper = RiotWrapper()
let lcsWeek: Week = rWrapper.getWeek("2014-07-07")
My getWeek method calls 3-4 functions which all parse JSON data in relation to the previous responses.
Ok, long story short question: I want to abort all Tasks if JSON or HTTP fails and fill my TableView just with an error message, how can I achieve this?
Something like: if error occurred -> Stop whatever you are doing -> return for example a null erm.. nil for week -> print error
Can someone help me? If someone have some lecture according this topic it will be fine also :D
Thanks in advance!
Btw: sorry for my "bad" english
All of your JSON parsing methods including getWeek should return a tuple with an optional return value and an error. If at any point you get an error in one of your methods from the JSON parsing, just immediately return the error with nil for the return value. Each method up the chain should check for an error from the previous methods and immediately return the error if it finds one:
func getWeek(string : String) -> (Week?, NSError) {
let (result, error) = self.otherMethod()
if error {
return (nil, error)
}
// continue happily ...
}
I would suggest having your function return an optional. It is easy to test and functions can be chained and shortcut.
func getWeek(string : String) -> Week? {
...
if error {
return nil
}
}
This can be quickly evaluated like this:
if let week = getWeek("2014-07-07") {
// handle success case
} else {
// handle nil
}
and check here for how to string together a number of functions that return optional:
https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html

Resources