Backendless - How To Get Objects From 'Data' - ios

How do I get all the objects from Backendless's database into a UITableView in my iOS app?
Looking at their Documentation, it doesn't clearly state how to get all objects. (I'm new to the platform)
Any help would be appreciated!

Here's how I do it in Swift (for my table of Blurb objects):
func retrieveBlurbs() {
let query = BackendlessDataQuery()
// Use backendless.persistenceService to obtain a ref to a data store for the class
let dataStore = self.backendless.persistenceService.of(Blurb.ofClass()) as IDataStore
dataStore.find(query, response: { (retrievedCollection) -> Void in
print("Successfully retrieved: \(retrievedCollection)")
self.blurbs = retrievedCollection.data as! [Blurb]
self.tableView.reloadData()
}) { (fault) -> Void in
print("Server reported an error: \(fault)")
}
}
I am also new to Backendless and really enjoying it! It's a lot like Parse, but better in a bunch of ways.

Start with this:
https://backendless.com/feature-16-data-retrieval-api-how-to-load-objects-from-an-mbaas-storage/
Then move on to this: https://backendless.com/feature-17-data-paging-or-how-to-efficiently-load-large-data-sets-in-a-mobile-app/
Both articles include concrete examples in Swift.

Try this:
- (void)viewDidLoad {
[super viewDidLoad];
[self getDataFromBackendless];
}
-(void)getDataFromBackendless {
#try {
BackendlessCollection *documents = [backendless.persistenceService of:[YOUR_TABLE_NAME class]];
currentPage =[documents getCurrentPage];
}
#catch (Fault *fault) {
NSLog(#"Server reported an error: %#", fault);
}
}
Then perform UITableView methods:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [currentPage count];
}

Related

Cannot access more than one value from function using PromiseKit Swift

TemplateClass.m
+ (AnyPromise *) promisefunctionReturnThreeValus:(NSString *)sampleName {
return [self anotherPromiseFunction:sampleName].then(^(NSMutableDictionary *sampleDict) {
DataArray *data = [DataArray dataArrayFromDict:sampleDict];
PropertyArray *property = [PropertyArray PropertyArrayFromDict:sampleDict];
if ([sampleDict objectForKey:NAME])
{
NameModel *name = [[NameModel alloc]initWithDictionary:[responseDict objectForKey:NAME]];
return (PMKManifold(data,property,name));
}
else
{
return (PMKManifold(data,property,nil));
}
});
}
well i can able to access this from objc using the below code
[TemplateClass promisefunctionReturnThreeValus:#"hello"].then(^(DataArray *data,PropertyArray *property,NameModel *name) {
//Here i can able to access the three values data,property and name
}
But when i try to access this from swift
TemplateClass.promisefunctionReturnThreeValus(sampleName: "hello").then{ data,property,name in
// it show me error " Contextual closure type '(Any?) -> AnyPromise' expects 1 argument, but 3 were used in closure body "
}
i can able to access only data but not the other two
i also tried debug it and print through log it show only the data of DataArray Object
lldb output
<DataArray : 0x1c0631340 count:1 value:{
"id" = 3631;
}
>

Binding a bool to multiple result in Swift

I am doing some experiments on ReactiveCocoa in both Objective-C language and Swift. However, I can not find a way to implement the same functionality with Swift
Here is the Objective-C version:
- (instancetype)init
{
self = [super init];
if (self) {
RAC(self, isLoginButtonEnabled) = [RACSignal combineLatest:#[RACObserve(self, username), RACObserve(self, password)] reduce:^(NSString *newUsername, NSString *newPassword) {
return #(newUsername.length && newPassword.length);
}];
}
return self;
}
I always got error when I do the same thing with Swift, BTW you need to import Swift-RAC-Macros in order to get RAC and RACOBserve in Swift:
override init() {
super.init()
RAC(self, "isLoginButtonEnabled", false) <~ RACSignal.combineLatest([RACObserve(self, "username"), RACObserve(self, "password")], reduce: {(newUsername: String?, newPassword: String?) -> AnyObject? in
return false;
})
}
For this I always get error:
(RAC, _) is not convertible to 'RACSignal'. Can anyone give me how to do that?

Parse Swift Custom Object Id?

I would like to create an object with a custom Object Id. The reason I want to do this is because I would like the save method to fail if it tries to create a row with the same data. For example: Parse automatically fails to save if you try to sign up with an email that is already taken. I would like the same thing to happen for data in a class that is not a User class.
Alternatively I could make things work if I knew how to do this
if(class contains column with "this string of data"){
do nothing}
else{
save "this string of data"}
What I'm doing is implementing an up-voting and down-voting system, and I don't want users to be able to vote more than once on a single post.
Each time a user votes, it would enter into parse a row of data with a column that is of string type that would be content of post + voter. and so if that combination of content of post + voter would try to be saved again, I want it to fail.
This is the code for a cell in the tableview. This is the downVote code. (the upVote code would be very similar)
//intVotes goes into a label with the amount of votes
//thisReview contains the content of the post
//downVote() increments number of votes by -1 in Parse
#IBAction func downVote(sender: AnyObject) {
var reviewQuery: PFQuery = PFQuery(className: "reviews")
reviewQuery.whereKey("content", equalTo: reviewTextView.text)
reviewQuery.findObjectsInBackgroundWithBlock{
(objects:[AnyObject]!, error:NSError!)->Void in
if error == nil{
for object in objects{
let review:PFObject = object as! PFObject
self.defaults.setValue(review["content"], forKey: "thisReview")
}
}
}
var vote:PFObject = PFObject(className: "votes")
if String(stringInterpolationSegment: vote.valueForKey("votes")) != String(stringInterpolationSegment: defaults.valueForKey("thisReview")) + String(stringInterpolationSegment: PFUser.currentUser()){
vote.setValue(String(stringInterpolationSegment: defaults.valueForKey("thisReview")) + String(stringInterpolationSegment: PFUser.currentUser()), forKey: "objectId")
vote.saveInBackgroundWithBlock {
(succeeded: Bool, error: NSError!) -> Void in
if error == nil {
self.downVote()
var intVotes: Int = self.votes.text!.toInt()!
intVotes = intVotes - 1
self.votes.text = "\(intVotes)"
} else {
println ("Failed")
}
}
}
else{
//do nothing
}
}
This ALMOST works, except the left side of the equation in the if statement (the vote.valueForKey part) returns nil every time.
You should just translate what Parse already shows you in their tutorial named "AnyPic" they implment and up/down voting "like button" system in ObjC, here's the main element translated to Swift you will have to import PAPCache.h/m PAPConstants.h/m and PAPUtility.h/m into your project and build out a bridging header to link to these files. From there, the only part you need to figure out is how to modify the following code to fit your needs, but this is already working, you just need to rearrange the variables, and change stuff to Optionals or NON-optionals to make this work for you. I'd assume that this method is THE BEST method since Parse uses this method themself in their ObjC BIG tutorial to show off everything which is the app "AnyPic", you'll have to declare a property in your UIVIewController of type PFObject and more, but this is the guts of the code. No one is going to give you the full code since this is going to take a lot of code and it would be easier if you did this in Swift instead of needing to do what I just did in the last 30 minutes. Bridging this to match the ObjC code is going to be laborious, but this is how it's done. Good luck!
What you need to declare, at minnimum:
var likeUsers : NSArray?
var likeButton: UIButton?
var someObject: PFObject?
Method:
func didTapLikeButtonAction(button: UIButton) {
var liked = Bool()
liked = !button.selected
button.removeTarget(self, action: "didTapLikeButtonAction(button)", forControlEvents: UIControlEvents.TouchUpInside)
var originalLikeUsersArray = NSArray()
originalLikeUsersArray = self.likeUsers!
var newLikeUsersSet = NSMutableSet(capacity: self.likeUsers!.count)
for id in self.likeUsers! {
if id.objectId != PFUser.currentUser()?.objectId {
newLikeUsersSet.addObject(id)
}
}
if liked {
PAPCache.sharedCache().incrementLikerCountForPhoto(self.someObject)
newLikeUsersSet.addObject(PFUser.currentUser()!)
} else {
PAPCache.sharedCache().decrementLikerCountForPhoto(self.someObject)
}
PAPCache.sharedCache().setPhotoIsLikedByCurrentUser(self.someObject, liked: liked)
likeUsers = newLikeUsersSet.allObjects
if liked {
PAPUtility.likePhotoInBackground(self.someObject, block: {(success: Bool, error: NSError?) -> Void in
if !success {
button.addTarget(self, action: "didTapLikeButtonAction(button)", forControlEvents:UIControlEvents.TouchUpInside)
self.likeUsers = originalLikeUsersArray
self.setLikeButtonState(true)
}
})
} else {
PAPUtility.unlikePhotoInBackground(self.someObject, block: {(success: Bool, error: NSError?) -> Void in
if !success {
button.addTarget(self, action: "didTapLikeButtonAction(button)", forControlEvents:UIControlEvents.TouchUpInside)
self.likeUsers = originalLikeUsersArray
self.setLikeButtonState(false)
}
})
}
}
LikeButtonFunction translated from ObjC
func setLikeButtonState(selected: Bool) {
if selected {
likeButton?.titleEdgeInsets = UIEdgeInsetsMake( -1.0, 0.0, 0.0, 0.0)
} else {
likeButton?.titleEdgeInsets = UIEdgeInsetsMake( 0.0, 0.0, 0.0, 0.0)
}
likeButton?.selected = selected
}
You will need to download the "Anypic" project from here:
https://parse.com/tutorials/anypic
and you will need to import into you Swift project, at minnimum, the following:
#import "PAPCache.h"
#import "PAPConstants.h"
#import "PAPUtility.h"
You will then need to recode the PAPCache, PAPUtility, and PAPConstants to fit your needs. Good luck, this will be a lot of coding due to Swift, but could be close to no coding if you were to use ObjC as Parse has said over and over again that they will not make a big push into Swift until it's battle tested. The last time they said this again was just two months ago in June.
The original code, from Objective-C, there's some things I didn't do for you since this is YOUR app and you will have to do these things yourself if you see it necessary, again, the ObjC code is done, but you chose to use Swift, so recoding what has already been provided basically, "out of the box" is what you are going to have to deal with:
- (void)didTapLikePhotoButtonAction:(UIButton *)button {
BOOL liked = !button.selected;
[button removeTarget:self action:#selector(didTapLikePhotoButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[self setLikeButtonState:liked];
NSArray *originalLikeUsersArray = [NSArray arrayWithArray:self.likeUsers];
NSMutableSet *newLikeUsersSet = [NSMutableSet setWithCapacity:[self.likeUsers count]];
for (PFUser *likeUser in self.likeUsers) {
if (![[likeUser objectId] isEqualToString:[[PFUser currentUser] objectId]]) {
[newLikeUsersSet addObject:likeUser];
}
}
if (liked) {
[[PAPCache sharedCache] incrementLikerCountForPhoto:self.photo];
[newLikeUsersSet addObject:[PFUser currentUser]];
} else {
[[PAPCache sharedCache] decrementLikerCountForPhoto:self.photo];
}
[[PAPCache sharedCache] setPhotoIsLikedByCurrentUser:self.photo liked:liked];
[self setLikeUsers:[newLikeUsersSet allObjects]];
if (liked) {
[PAPUtility likePhotoInBackground:self.photo block:^(BOOL succeeded, NSError *error) {
if (!succeeded) {
[button addTarget:self action:#selector(didTapLikePhotoButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[self setLikeUsers:originalLikeUsersArray];
[self setLikeButtonState:NO];
}
}];
} else {
[PAPUtility unlikePhotoInBackground:self.photo block:^(BOOL succeeded, NSError *error) {
if (!succeeded) {
[button addTarget:self action:#selector(didTapLikePhotoButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[self setLikeUsers:originalLikeUsersArray];
[self setLikeButtonState:YES];
}
}];
}
[[NSNotificationCenter defaultCenter] postNotificationName:PAPPhotoDetailsViewControllerUserLikedUnlikedPhotoNotification object:self.photo userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:liked] forKey:PAPPhotoDetailsViewControllerUserLikedUnlikedPhotoNotificationUserInfoLikedKey]];
}
- (void)didTapLikerButtonAction:(UIButton *)button {
PFUser *user = [self.likeUsers objectAtIndex:button.tag];
if (delegate && [delegate respondsToSelector:#selector(photoDetailsHeaderView:didTapUserButton:user:)]) {
[delegate photoDetailsHeaderView:self didTapUserButton:button user:user];
}
}
- (void)didTapUserNameButtonAction:(UIButton *)button {
if (delegate && [delegate respondsToSelector:#selector(photoDetailsHeaderView:didTapUserButton:user:)]) {
[delegate photoDetailsHeaderView:self didTapUserButton:button user:self.photographer];
}
}
The ObjC code from above comes from the file "PAPPhotoDetailsHeaderView.m" of the Parse.com AnyPic github repo and you can see their OBJECTIVE-C tutorial on this on their web site at the web site I've listed above.
And, by the way, this DOES work for me, and it does compile for me, but I don't use Swift, so this is useless to me, but if you set things up correctly, you don't need to mess around with the PAPCache, PAPConstants, and PAPUtility. But this assumes you are well versed in all things Parse. Anyway, good luck.
I just added the likeButtonOn/Off function, translated from ObjC

NSKeyedUnarchiver error handling - prevent crash in Swift

Since Swift currently doesn't have try-catch, how am I supposed to prevent crashes with bad data in this line of code?
var myObject = NSKeyedUnarchiver.unarchiveObjectWithData(data) as MyClass
UPDATE
I created a very simple case in a playground for demonstration. Assume we don't know what's in data, how can I catch the SIGABRT on the second line? Is there no way to check to make sure it is possible to unarchive an NSData object before calling unarchiveObjectWithData?
var data = "foo bar".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
if let unarc = NSKeyedUnarchiver.unarchiveObjectWithData(data) { // Execution was interrupted: signal SIGABRT
}
I think your best bet for now, until Apple updates the implementation of NSKeyedUnarchiver to not use exceptions or adds exception support to Swift, you are going to have to use an Objective-C wrapper to try-catch.
You can see an example of a wrapper here:
https://medium.com/swift-programming/adding-try-catch-to-swift-71ab27bcb5b8
Essentially, you can introduce a single Objective-C function or class that will allow you to use a try-catch block from Swift. I like implementing the above example as an initializer to make it cleaner in Swift:
// In Objective-C
// ----------------------
#interface try: NSObject
- (id)initWithTry:(void(^)())try catch:(void(^)(NSException *exception))catch finally:(void(^)())finally;
#end
#implementation try
- (id)initWithTry:(void(^)())try catch:(void(^)(NSException *exception))catch finally:(void(^)())finally
{
self = [super init];
if (self) {
#try {
try ? try() : nil;
}
#catch (NSException *exception) {
catch ? catch(exception) : nil;
}
#finally {
finally ? finally() : nil;
}
}
return self;
}
#end
// From Swift (make sure you import the objc header in your bridging header
// ----------------------
var data = "foo bar".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
try(
try: { () -> Void in
if let unarc: AnyObject = NSKeyedUnarchiver.unarchiveObjectWithData(data) { // Execution was interrupted: signal SIGABRT
println(unarc)
}
},
catch: { exception in
println("Failed to parse data: \(exception)")
},
finally: nil
)

StrongLoop Loopback example in Swift

I'm trying to implement the example LoopBack iOS app in Swift
Create a LoopBack iOS app: part one
and I'm having some trouble translating from the ObjectiveC
- (void) getBooks
{
//Error Block
void (^loadErrorBlock)(NSError *) = ^(NSError *error){
NSLog(#"Error on load %#", error.description);
};
void (^loadSuccessBlock)(NSArray *) = ^(NSArray *models){
NSLog(#"Success count %d", models.count);
self.tableData = models;
[self.myTable reloadData];
};
//This line gets the Loopback model "book" through the adapter defined in AppDelegate
LBModelRepository *allbooks = [[booksAppDelegate adapter] repositoryWithModelName:prototypeName];
//Logic - Get all books. If connection fails, load the error block, if it passes, call the success block and pass allbooks to it.
[allbooks allWithSuccess:loadSuccessBlock failure:loadErrorBlock];
};
Here's my version
func getBooks() {
var errorBlock = {
(error: NSError!) -> Void in
NSLog("Error on load %#", error.description)
}
var successBlock = {
(models: NSArray!) -> Void in
NSLog("Success count %d", models.count)
self.tableData = models
self.booksTable.reloadData()
}
// get the "book" model
var allBooks: LBModelRepository = adapter.repositoryWithModelName(prototypeName)
// get all books
allBooks.allWithSuccess(successBlock, errorBlock)
}
but I get a compiler error on the call to allWithSuccess:
Cannot convert the expressions type 'Void' to type 'LBModelAllSuccessBlock!'
What am I missing?
UPDATE:
If I declare the success block as follows, it works:
var successBlock = {
(models: AnyObject[]!) -> () in
self.tableData = models
self.booksTable.reloadData()
}
Thanks for the answer!!!!
If anyone is looking for the last version of Swift and LoopBack iOS SDK, it worked for me like this:
func getBooks() {
// Error Block
let errorBlock = {
(error: NSError!) -> Void in
NSLog("Error on load %#", error.description)
}
// Success Block
let successBlock = {
(models: [AnyObject]!) -> () in
self.tableData = models
self.myTable.reloadData()
}
// This line gets the Loopback model "book" through the adapter defined in AppDelegate
let allBooks:LBPersistedModelRepository = AppDelegate.adapter.repositoryWithModelName(prototypeName, persisted: true) as! LBPersistedModelRepository
// Logic - Get all books. If connection fails, load the error block, if it passes, call the success block and pass allbooks to it.
allBooks.allWithSuccess(successBlock, failure: errorBlock)
}

Resources