Parse/Swift getObjectInBackgroundWithId query not working - xcode

I am trying to run the query to get object in background with ID but when I run the method query.getObjectInBackgroundWithId , I am getting the error message:
"Cannot invoke 'getObjectInBackgroundWithId' with an argument list of type (string, block: (PFObject!,NSError?) -> Void"
The same thing happens when I use user.signUpInBackgroundWithBlock so I'm thinking maybe Xcode updated some of the features while using 'block's and now maybe the syntax is different? Any ideas?
Here's a snippet of my code:
http://imgur.com/1CvfhbU

YES!!! Thank you!
The new sample code for getObject is:
query.getObjectInBackgroundWithId("Oaq79bhv53") {
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil && gameScore != nil {
println(gameScore)
} else {
println("error")
}
}

I figured it out!
user.signUpInBackgroundWithBlock{(succeeded: Bool, signUpError: NSError?) -> Void in

Swift 4.2:
query.getObjectInBackground(withId: "YourId") { (gameScore, error) in
if error == nil {
// Success!
print(gameScore)
} else {
// Fail!
}
}

Related

logInWithReadPermissions(_:handler:)' is deprecated: use logInWithReadPermissions:fromViewController:handler: instead

Using the latest XCode, I'm getting this error:
'logInWithReadPermissions(_:handler:)' is deprecated:
use logInWithReadPermissions:fromViewController:handler: instead'
How would I alternatively re-format my code? here is the whole function that it is in:
#IBAction func fbBtnPressed(sender: UIButton!) {
let facebookLogin = FBSDKLoginManager()
facebookLogin.logInWithReadPermissions(["email"]) {
(facebookResult: FBSDKLoginManagerLoginResult!,facebookError: NSError!) in
print("Facebook login failed. Error \(facebookError)")
}
}
Xcode 8.2 beta (8C30a) :
fbLoginManager.logIn(withReadPermissions:["email"], from: self, handler: {
(result, error) -> Void in
if (error == nil){
let fbloginresult : FBSDKLoginManagerLoginResult? = result
if(fbloginresult?.isCancelled)! {
//Show Cancel alert
} else if(fbloginresult?.grantedPermissions.contains("email"))! {
//self.returnUserData()
//fbLoginManager.logOut()
}
}
})
Figured it out guys! If anyone is lurking on this post, here is the new code:
#IBAction func fbBtnPressed(sender: UIButton!) {
let facebookLogin = FBSDKLoginManager()
facebookLogin.logInWithReadPermissions(["email"], fromViewController: self) { (facebookResult: FBSDKLoginManagerLoginResult!, facebookError: NSError!) -> Void in
print("Facebook login failed. Error \(facebookError)")
}
}
If your fbBtnPressed function is in a view controlle class, just pass self to the fromViewController parameter.
facebookLogin.logInWithReadPermissions(["email"], fromViewController: self) { ... }
A note though, it's encouraged in Swift and Obj-C that your function names prioritize readability over being compact. For example, I would name your button handler facebookLoginButtonPressed. It's longer but much more readable.

try catch not working in swift

This should be simple and obvious but try catch in swift2 frustrating me. here is my code.
#IBAction func btnAdd_TouchDown(sender: AnyObject) {
do { try AddNewNotesToList() } catch{
if(Ex.UnknownError != "")
{
Error(Ex.UnknownError)
}
}
}
func AddNewNotesToList() throws
{
var obj: TreatmentNotesDTO = TreatmentNotesDTO()
obj.therapist_id = Int(TherapistId)! // getting error here
return
}
Error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Debugger should go to catch but its breaking up. I am from c# and just started swift2. Any help
I would suggest you to use guard to catch such errors:
guard let therapistID = Int(TherapistId) else {
print(TherapistId + " cannot be converted to an Int")
return
// or mark function as throws and return an error
throw NSError(domain: TherapistId + " cannot be converted to an Int", code: 0, userInfo: nil)
}
obj.therapist_id = therapistID
Note that Int(TherapistId)! doesn't throw an error with throws. It is a fatal error which stops program execution.

How to unit test throwing functions in Swift?

How to test wether a function in Swift 2.0 throws or not? How to assert that the correct ErrorType is thrown?
EDIT: Updated the code for Swift 4.1 (still valid with Swift 5.2)
Here's the latest Swift version of Fyodor Volchyok's answer who used XCTAssertThrowsError:
enum MyError: Error {
case someExpectedError
case someUnexpectedError
}
func functionThatThrows() throws {
throw MyError.someExpectedError
}
func testFunctionThatThrows() {
XCTAssertThrowsError(try functionThatThrows()) { error in
XCTAssertEqual(error as! MyError, MyError.someExpectedError)
}
}
If your Error enum has associated values, you can either have your Error enum conform to Equatable, or use the if case statement:
enum MyError: Error, Equatable {
case someExpectedError
case someUnexpectedError
case associatedValueError(value: Int)
}
func functionThatThrows() throws {
throw MyError.associatedValueError(value: 10)
}
// Equatable pattern: simplest solution if you have a simple associated value that can be tested inside 1 XCTAssertEqual
func testFunctionThatThrows() {
XCTAssertThrowsError(try functionThatThrows()) { error in
XCTAssertEqual(error as! MyError, MyError.associatedValueError(value: 10))
}
}
// if case pattern: useful if you have one or more associated values more or less complex (struct, classes...)
func testFunctionThatThrows() {
XCTAssertThrowsError(try functionThatThrows()) { error in
guard case MyError.associatedValueError(let value) = error else {
return XCTFail()
}
XCTAssertEqual(value, 10)
// if you have several values or if they require more complex tests, you can do it here
}
}
At least of Xcode 7.3 (maybe earlier) you could use built-in XCTAssertThrowsError():
XCTAssertThrowsError(try methodThatThrows())
If nothing is thrown during test you'll see something like this:
If you want to check if thrown error is of some concrete type, you could use errorHandler parameter of XCTAssertThrowsError():
enum Error: ErrorType {
case SomeExpectedError
case SomeUnexpectedError
}
func functionThatThrows() throws {
throw Error.SomeExpectedError
}
XCTAssertThrowsError(try functionThatThrows(), "some message") { (error) in
XCTAssertEqual(error as? Error, Error.SomeExpectedError)
}
Given the following functions and declarations:
enum SomeError: ErrorType {
case FifthError
case FirstError
}
func throwingFunction(x: Int) throws {
switch x {
case 1:
throw SomeError.FirstError
case 5:
throw SomeError.FifthError
default:
return
}
}
This function will throw a FifthError if 5 is given to the function and FirstError if 1 is given.
To test, that a function successfully runs the unit test could look as follows:
func testNotError() {
guard let _ = try? throwingFunction(2) else {
XCTFail("Error thrown")
return
}
}
The let _ may also be replaced by any other name, so you can further test the output.
To assert that a function throws, no matter what ErrorType the unit test could look like this:
func testError() {
if let _ = try? throwingFunction(5) {
XCTFail("No error thrown")
return
}
}
If you want to test for a specific ErrorType it's done with a do-catch-statement. This is not the best way compared to other languages.
You have to make sure that you...
return in the catch for the correct ErrorType
XCTFail() and return for all other catch
XCTFail() if no catch is executed
Given this requirements a test case could look like this:
func testFifthError() {
do {
try throwingFunction(5)
} catch SomeError.FifthError {
return
} catch {
XCTFail("Wrong error thrown")
return
}
XCTFail("No error thrown")
}
Swift 4.1 Error throwing Test for associated values
enum ParseError: Error, Equatable {
case unexpectedArgument(String)
}
func testWithNoSchemaButWithOneArgument() {
XCTAssertThrowsError(try Args(withSchema: "", andArguments: ["-x"])) { error in
XCTAssertEqual(error as? ParseError, ParseError.unexpectedArgument("Argument(s) -x unexpected."))
}
}
You can use this function:
func XCTAssertThrowsError<T, E: Error & Equatable>(
_ expression: #autoclosure () throws -> T,
error: E,
in file: StaticString = #file,
line: UInt = #line
) {
var thrownError: Error?
XCTAssertThrowsError(
try expression(),
file: file,
line: line) {
thrownError = $0
}
XCTAssertTrue(
thrownError is E,
"Unexpected error type: \(type(of: thrownError))",
file: file,
line: line
)
XCTAssertEqual(
thrownError as? E,
error,
file: file,
line: line
)
}
Example:
XCTAssertThrowsError(try funcThatThrowsSpecificError(), error: SpecificErrorEnum.someError)

do try catch swift 2

HI i am a little confused about how to transfer if_else error handling to do try catch successfully.
Here is my code.
let error : NSError?
if(managedObjectContext!.save()) {
NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
if error != nil {
print(error?.localizedDescription)
}
}
else {
print("abort")
abort()
}
and now i converted to swift 2.0 like this
do {
try managedObjectContext!.save()
}
catch {
NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
print((error as NSError).localizedDescription)
}
I am confused about where to print abort and do the abort() function
Any idea~? Thanks a lot
Rewriting your code to work the same as your original code
do {
try managedObjectContext!.save()
//this happens when save did pass
NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
//this error variable has nothing to do with save in your original code
if error != nil {
print(error?.localizedDescription)
}
}
catch {
//this happens when save() doesn't pass
abort()
}
what you probably want to write is the following:
do {
try managedObjectContext!.save()
//this happens when save did pass
NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
}
catch let saveError as NSError {
//this happens when save() doesn't pass
print(saveError.localizedDescription)
abort()
}
Everything within do {} is good, everything within catch {} is bad
do {
try managedObjectContext!.save()
NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
}
catch let error as NSError {
print(error.localizedDescription)
abort()
}
use either the error handling or the abort() statement

Signing Up Parse User with Swift 1.2

I use the signing up feature of Parse.com just as describe here. Here's my code:
user.signUpInBackgroundWithBlock {
(succeeded: Bool!, error: NSError!) -> Void in
if error == nil {
// Hooray! Let them use the app now.
} else {
let errorString = error.userInfo["error"] as NSString
// Show the errorString somewhere and let the user try again.
}
}
}
Unfortunately, I've updated my project from swift 1.1 to swift 1.2 and get the following compiler error:
Function signature '(Bool!, NSError!)->void is not compatible with
excepted type '#objc_block (Bool,NSError!)->Void'
it's on the following line:
user.signUpInBackgroundWithBlock {
(succeeded: Bool!, error: NSError!) -> Void in
Does anybody know how can I fox that ? Thanks !
Your succeeded variable is a 'Bool!' but what the block returns is a 'Bool' (without exclamation mark).
The solution would be:
user.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError!) -> Void in
if error == nil {
// Hooray! Let them use the app now.
} else {
let errorString = error.userInfo["error"] as NSString
// Show the errorString somewhere and let the user try again.
}
}
}
Too see more about optionals go to the apple doc
I had the same problem with save in background with block. It looks like parse returns a "Bool not a Bool!"...however error is an NSError? unless you "!" it.
something.saveInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
code
}

Resources