Return Value from Function Swift - objective-c

I know this is probably a simple queston, I would like to return the value of currentLocGeoPoint and return the array of Objects which is of type PFObject.
Tried to save it as a global variable, but it doesn't work because it is asynchronous and doesn't take a value yet. Returns empty.
Tried to return currentLocGeoPoint and changed Void in to PFGeoPoint in. Gives error: PFGeoPoint is not convertible to 'Void'
So I'm not sure how I can fetch the variable currentLocGeoPoint.
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in
if (error != nil) {
println("Error:" + error.localizedDescription)
//return
}
if placemarks.count > 0 {
let pm = placemarks[0] as CLPlacemark
self.displayLocationInfo(pm)
currentLoc = manager.location
currentLocGeoPoint = PFGeoPoint(location:currentLoc)
var query = PFQuery(className:"Bar")
query.whereKey("BarLocation", nearGeoPoint:currentLocGeoPoint, withinMiles:10)
query.limit = 500
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if objects != nil {
} else {
println("error: \(error)")
}
}
} else {
println("error: \(error)")
}
})
}

I don't understand the notion of "I want to return currentLocGeoPoint". Return it to what? You're in a CLLocationManagerDelegate method, so there's no one to return it to.
What you could do, though, is, when the request is done (i.e. within this closure), call some other function that needed the currentLocGeoPoint. Or you could update the UI to reflect the updated information (make sure to dispatch that update to the main thread, though). Or, if you have other view controllers or model objects that need to know about the new data, you might post a notification, letting them know that there is an updated currentLocGeoPoint. But within this method, there's no one to whom you would "return" the data.

You could assign it to a stored property of your class. Just use
self.<property> = currentLocGeoPoint

Related

if error == nil parse swift

I'm trying to check when I save an object to my parse serve if something goes wrong. But I have two options and I have three options and I don't know the difference. I have these three options (if error == nil, or if object != nil, or if error == nil and object != nil). Which one should I use. Thanks
Option #1
let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
if error == nil{
}
)}
Option #2
let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
if object != nil{
}
)}
Option #3
let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
if error == nil && object != nil{
}
)}
I suggest and encourage you to use guard statement, which as made for such situations.
//Always safely unwrap optional value:
if let user = PFUser.current(){
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
guard success, error == nil else {
//handle error somehow...(print or whatever...)
return
}
//Continue here as everything is fine...
)}
}
Better to use different handlers for success and for failure:
func saveInBackground(success: () -> Void, failure: (Error?) -> Void) {
/* do whatever you need */
if saved {
success()
} else {
failure(saveError)
}
}
saveInBackground(success: {
/* saving was succeed */
}, failure: { (error) in
/* saving was failed */
})
There should never be an error when the save operation succeeds, as a general rule of thumb, it depends on the next steps of your implementation. None of the approach is invalid, i would still recommend that you check the ‘happy value’, object, succeed dtc... before checking the error

In Objective C, what happens if we pass nil or null to #synchronized() block?

Usually we will pass an object to #synchronized() block for unique reference. for example,
+(id)sharedDBHandler
{
#synchronized (self) {
if (sDBHandler == nil) {
sDBHandler = [self new];
}
}
return sDBHandler;
}
what happens if we pass nil to it?
It doesn't #synchronize() at all. No locks taken. No-op. Undefined behavior.
Perfectly valid question, btw, regardless of whether the code is antiquated and no longer the correct means of generating a singleton.
From the github repository. While not a documented claim, breaking this policy would cause compatibility hell.
int objc_sync_enter(id obj)
{
int result = OBJC_SYNC_SUCCESS;
if (obj) {
SyncData* data = id2data(obj, ACQUIRE);
assert(data);
data->mutex.lock();
} else {
// #synchronized(nil) does nothing
if (DebugNilSync) {
_objc_inform("NIL SYNC DEBUG: #synchronized(nil); set a breakpoint on objc_sync_nil to debug");
}
objc_sync_nil();
}
return result;
}
Where:
BREAKPOINT_FUNCTION(
void objc_sync_nil(void)
);

Converting objective-c block to Swift closure

I am trying to convert this Objective-C block into Swift:
[self.client downloadEntity:#"Students" withParams: nil success:^(id response) {
// execute code
}
failure:^(NSError *error) {
// Execute code
}];
This is my code in Swift, but the syntax seems to be a bit off:
client.downloadEntity("Students", withParams: nil, success: {(students: [AnyObject]!) -> Void in
print("here")
}, failure: { (error: NSError!) -> Void! in
print ("here")
}
This is giving me a few compilation errors:
Value of 'AnyObject' has no member 'downloadEntity'
It is complaining about the lack of commas (,) right after the failure part of the code
Try this:
client.downloadEntity("Student", withParams: nil,
success: { (responseObj) -> Void in
print("success: \(responseObj)")
},
failure: { (errorObj) -> Void in
print("treat here (in this block) the error! error:\(errorObj)")
})
You need to switch to the new Swift error syntax, and you can also using trailing closures. I had to use a bool for the example to show how you would call your success closure, or you would throw an error.
var wasSuccessful = true // This is just here so this compiles and runs
// This is a custom error type. If you are using something that throws an
// NSError, you don't need this.
enum Error:ErrorType {
case DownloadFailed
}
// Hopefully you have control over this method and you can update
// the signature and body to something similar to this:
func downloadEntity(entityName: String, success: ([AnyObject]) -> Void) throws {
let students = [AnyObject]()
// download your entity
if wasSuccessful {
// Call your success completion handler
success(students)
}
else {
throw Error.DownloadFailed
}
}
When you have a function that can throw an error, you need to call it with try inside a do/catch block.
// Calling a function that can throw
do {
try downloadEntity("Students") { students in
print("Download Succeded")
}
}
catch Error.DownloadFailed {
print("Download Failed")
}
// If you are handling NSError use this block instead of the one above
// catch let error as NSError {
// print(error.description)
// }

Throwing on unwrapping nil optional

Consider the following code:
enum MyErrorType:ErrorType {
case BadTimes
}
var mightHaveAValue: String?
do {
if let value = mightHaveAValue {
// do stuff with value
} else {
throw MyErrorType.BadTimes
}
// do stuff with NSFileManager using mightHaveAValue which might throw
} catch {
// handle error
}
...in which I have a large do/try/catch block. In this instance the error handling will be the same, whether mightHaveAValue is empty or something bad happens with NSFileManager later on. So it makes sense to re-use the error handling code.
Is this the cleanest approach going in Swift2, or is there some way I can automatically throw/catch on unwrapping an optional with no value?
It looks ok, but it's even better with guard let instead of if let because it lets you use the unwrapped value in the main do block instead of having to work inside an if let branch. You can also use several catch branches to handle different error types.
do {
guard let value = mightHaveAValue else {
throw MyErrorType.BadTimes
}
// do stuff with value
} catch let error as MyErrorType {
// handle custom error
} catch let error as NSError {
// handle generic NSError
}
There is no automatic way to handle unwrapping optionals, you have to use one of the many known ways: if let, guard let, nil coalescing, etc.
Maybe just use an extension like this 🤔
extension Optional {
func throwing() throws -> Wrapped {
if let wrapped = self {
return wrapped
} else {
throw NSError("Trying to access non existing value")
}
}
}

Hide Activity Indicator Does Not Work

The activity indicator starts, but does not stop when the hide function is called. I've tried putting the hide function in various places, and it still does not hide.
Hide activity indicator: Q0ViewController().hideActivityIndicator(self.view)
I'm using the swift utility function found here:
https://github.com/erangaeb/dev-notes/blob/master/swift/ViewControllerUtils.swift
Start activity indicator
override func viewDidLoad() {
super.viewDidLoad()
Q0ViewController().showActivityIndicator(self.view)
self.locationManager.delegate = self //location manager start
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
Hide activity indicator after query:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in
if (error != nil) {
println("Error:" + error.localizedDescription)
//return
}
if placemarks.count > 0 {
let pm = placemarks[0] as CLPlacemark
self.displayLocationInfo(pm)
currentLoc = manager.location
currentLocGeoPoint = PFGeoPoint(location:currentLoc)
var query = PFQuery(className:"test10000")
query.whereKey("RestaurantLoc", nearGeoPoint:currentLocGeoPoint, withinMiles:100) //filter by miles
query.limit = 1000 //limit number of results
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if objects != nil {
unfilteredRestaurantArray = objects
originalUnfilteredArray = objects
println(objects)
} else {
println("error: \(error)")
}
Q0ViewController().hideActivityIndicator(self.view) //HIDE
}
} else {
println("error: \(error)")
}
})
}
It is not an issue with the main queue as dispatch_after(DISPATCH_TIME_NOW, dispatch_get_main_queue(), { ()->() in does not resolve the issue.
Looks like you're creating a new instance of the "Q0ViewController" each time.
Instead I would suggest retaining the initial instance as a property on your class:
// As a variable on the class instance
let myViewController = Q0ViewController()
// Initially show the activity indicator
self.myViewController.showActivityIndicator(self.view)
// Hide the activity indicator
self.myViewController.hideActivityIndicator(self.view)
Hopefully this helps!
Similar to what Joshua suggested, just replaced:
Q0ViewController().showActivityIndicator(self.view)
and
Q0ViewController().hideActivityIndicator(self.view)
To:
self.showActivityIndicator(self.view)
and
self.hideActivityIndicator(self.view)