Converting objective-c block to Swift closure - objective-c

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)
// }

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

get error in swift side form objective-c side

I try to get error object from this function of ZipArchive
guard ZipArchive.unzipFileAtPath(filePath as String,toDestination: folderPath as String,overwrite: true, password: nil,error: whatShouldGoHere) else
{
throw whatShouldGoHere
}
My question is how to get back whatShouldGoHere form this unzipFileAtPath Objective-C function ?
I note that in the define of unzipFileAtPath function have access NSError object to whatShouldGoHere parameter
NSError *err = [NSError errorWithDomain:#"ZipArchiveErrorDomain" code:-1 userInfo:userInformation];
if (error) {
error = err;
}
I will use this library ZipArchive to show you how to get the error object from calling objective-c functions.
In this library, it also has the same above function.
+ (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination overwrite:(BOOL)overwrite password:(NSString *)password error:(NSError **)error;
In swift 2.1, you can use Handling Errors Using Do-Catch to get the error object.
do {
try SSZipArchive.unzipFileAtPath(filePath, toDestination: folderPath, overwrite: true, password: nil)
} catch {
print(error)
}
If you want to write a function to rethrow the error received from ZipArchive don't guard the boolean result but catch the error in a do - catch block and throw it.
do {
try SSZipArchive.unzipFileAtPath(filePath as String,
toDestination: folderPath as String,
overwrite: true,
password: nil)
} catch let error as NSError {
throw error
}

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")
}
}
}

Using XCTest, how can one chain together multiple discrete sequences of { expectations -> wait }?

The documentation for XCTest waitForExpectationsWithTimeout:handler:, states that
Only one -waitForExpectationsWithTimeout:handler: can be active at any given time, but multiple discrete sequences of { expectations -> wait } can be chained together.
However, I have no idea how to implement this, nor can I find any examples. I'm working on a class that first needs to find all available serial ports, pick the correct port and then connect to the device attached to that port. So, I'm working with at least two expectations, XCTestExpectation *expectationAllAvailablePorts and *expectationConnectedToDevice. How would I chain those two?
I do the following and it works.
expectation = [self expectationWithDescription:#"Testing Async Method Works!"];
[AsynClass method:parameter callbackFunction:^(BOOL callbackStatus, NSMutableArray* array) {
[expectation fulfil];
// whatever
}];
[self waitForExpectationsWithTimeout:5 handler:^(NSError *error) {
if (error) {
XCTFail(#"Expectation Failed with error: %#", error);
}
NSLog(#"expectation wait until handler finished ");
}];
// do it again
expectation = [self expectationWithDescription:#"Testing Async Method Works!"];
[CallBackClass method:parameter callbackFunction:^(BOOL callbackStatus, NSMutableArray* array) {
[expectation fulfil];
// whatever
}];
[self waitForExpectationsWithTimeout:5 handler:^(NSError *error) {
if (error) {
XCTFail(#"Expectation Failed with error: %#", error);
}
NSLog(#"expectation wait until handler finished ");
}];
swift
let expectation1 = //your definition
let expectation2 = //your definition
let result = XCTWaiter().wait(for: [expectation1, expectation2], timeout: 10, enforceOrder: true)
if result == .completed {
//all expectations completed in order
}
Assigning my expectation to a weak variable worked for me.
This seems to be working for me in Swift 3.0 as well.
let spyDelegate = SpyDelegate()
var asyncExpectation = expectation(description: "firstExpectation")
spyDelegate.asyncExpectation = asyncExpectation
let testee = MyClassToTest(delegate: spyDelegate)
testee.myFunction() //asyncExpectation.fulfill() happens here, implemented in SpyDelegate
waitForExpectations(timeout: 30.0) { (error: Error?) in
if let error = error {
XCTFail("error: \(error)")
}
}
asyncExpectation = expectation(description: "secoundExpectation")
spyDelegate.asyncExpectation = asyncExpectation
testee.delegate = spyDelegate
testee.myOtherFunction() //asyncExpectation.fulfill() happens here, implemented in SpyDelegate
waitForExpectations(timeout: 30.0) { (error: Error?) in
if let error = error {
XCTFail("error: \(error)")
}
}
Within a class that extends XCTestCase you can use wait(for:timeout:) like this:
let expectation1 = self.expectation(description: "expectation 1")
let expectation2 = self.expectation(description: "expectation 2")
let expectation3 = self.expectation(description: "expectation 3")
let expectation4 = self.expectation(description: "expectation 4")
// ...
// Do some asyc stuff, call expectation.fulfill() on each of the above expectations.
// ...
wait(for:[expectation1,expectation2,expectation3,expectation4], timeout: 8)

Return Value from Function Swift

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