Connect to database from Xcode (iOS Ipad APP)

-(void)getNewSessionWithEmail:(NSString*)email Password:(NSString*)password BaseUrl:(NSString*)baseUrl{
    
    NSString *baseDspUrl=baseUrl;
    [self.progressView setHidden:NO];
    [self.activityIndicator startAnimating];
    
    NIKApiInvoker *_api = [NIKApiInvoker sharedInstance];
    NSString *serviceName = @"user"; // your service name here
    NSString *apiName = @"session"; // rest path
    NSString *restApiPath = [NSString stringWithFormat:@"%@/%@/%@",[self setBaseUrlPath:baseUrl],serviceName,apiName];
    NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
    NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init];
    [headerParams setObject:kApplicationName forKey:@"X-DreamFactory-Application-Name"];
    NSString* contentType = @"application/json";
    
    NSDictionary *requestBody = @{@"email": email, @"password": password};
    
    [_api dictionary:restApiPath method:@"POST" queryParams:queryParams body:requestBody headerParams:headerParams contentType:contentType completionBlock:^(NSDictionary *output, NSError *error) {
        NSLog(@"ERROR %@",error);
        NSLog(@"OUTPUT %@",[output objectForKey:@"id"]);
        dispatch_async(dispatch_get_main_queue(),^ (void){
            [self.progressView setHidden:YES];
            [self.activityIndicator stopAnimating];
            if(output){
                NSString *SessionId=[output objectForKey:@"session_id"];
                [[NSUserDefaults standardUserDefaults] setValue:baseDspUrl forKey:kBaseDspUrl];
                [[NSUserDefaults standardUserDefaults] setValue:SessionId forKey:kSessionIdKey];
                [[NSUserDefaults standardUserDefaults] setValue:email forKey:kUserEmail];
                [[NSUserDefaults standardUserDefaults] setValue:password forKey:kPassword];
                [[NSUserDefaults standardUserDefaults] synchronize];
                //[self displayInitialViewController];
            }else{
                
                UIAlertView *message=[[UIAlertView alloc]initWithTitle:@"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:@"ok" otherButtonTitles: nil];
                [message show];
            }
            
        });
        
    }];
    NSLog(@"%@==%@",@"New SESS:",[[NSUserDefaults standardUserDefaults] valueForKey:kSessionIdKey]);
    NSLog(@"%@==%@",@"New REST:",restApiPath);
    
}

-(void)getTodoListContentFromServer{
    NSString  *swgSessionId=[[NSUserDefaults standardUserDefaults] valueForKey:kSessionIdKey];
    if (swgSessionId.length>0) {
        [self showProgressView:YES];
        NIKApiInvoker *_api = [NIKApiInvoker sharedInstance];
        NSString *serviceName = @"eMomentsServiceAPI"; // your service name here
        
        //NSString *apiName = kTableName; // rest path
        NSString *apiName = kTableName;
        NSString *restApiPath = [NSString stringWithFormat:@"%@/%@/%@",baseUrl,serviceName,apiName];
        NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
        queryParams[@"include_count"] = [NSNumber numberWithBool:TRUE];
        
        NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init];
        [headerParams setObject:kApplicationName forKey:@"X-DreamFactory-Application-Name"];
        [headerParams setObject:swgSessionId forKey:@"X-DreamFactory-Session-Token"];
        NSString* contentType = @"application/json";
        id bodyDictionary = nil;
        [self.progressView setHidden:NO];
        [self.activityIndicator startAnimating];
        [_api dictionary:restApiPath method:@"GET" queryParams:queryParams body:bodyDictionary headerParams:headerParams contentType:contentType completionBlock:^(NSDictionary *responseDict, NSError *error) {
            NSLog(@"Error %@",error);
            dispatch_async(dispatch_get_main_queue(),^ (void){
                [self showProgressView:NO];
            });
            if (error) {
                dispatch_async(dispatch_get_main_queue(),^ (void){
                    [self.navigationController popToRootViewControllerAnimated:YES];
                });
                
            }else{
                [self.todoListContentArray removeAllObjects];
                for (NSDictionary *recordInfo in [responseDict objectForKey:@"record"]) {
                    TODORecord *newRecord=[[TODORecord alloc]init];
                    [newRecord setRecord_Id:[recordInfo objectForKey:@"id"]];
                    [newRecord setRecord_Task:[recordInfo objectForKey:@"name"]];
                    [newRecord setRecord_Complete:[recordInfo objectForKey:@"complete"]];
                    [self.todoListContentArray addObject:newRecord];
                }
                
                dispatch_async(dispatch_get_main_queue(),^ (void){
                    [self.todoListTableView reloadData];
                    [self.todoListTableView setNeedsDisplay];
                });
            }
            
        }];
        
        
    }else{
        
    }
    
}

This code is taken from the IOS SDK app.

Can any kind soul help me figure out what is the rest path for my app? Thanks

I have the same issue.

My problem is figuring out the REST API NAMES, header, api, service etcs. Please help, I’m on a tight.

Have you read the iOS SDK README? Under the section header “This SDK provides APIs to call any RESTful service in DreamFactory.” you will observe that each call simply concatenates the service name and then the REST path for the call. E.g., for a POST /rest/user/session (which is a login call):

NSString *serviceName = @"user"; // your service name here
    NSString *apiName = @"session"; // rest path
    NSString *restApiPath = [NSString stringWithFormat:@"%@/%@/%@",[self setBaseUrlPath:self.urlTextField.text],serviceName,apiName];

So even the comments in the code make it clear that, in a case you wanted to call a different service called “remotemysql” and wanted to pull a field named “lastname” from a table called “members” you would simply construct a new SWGDbApi object similar to the ones that exist in the SDK, and where "user" is above put "remotemysql" and where "session" is above put "members/lastname".

Basic construction of REST API paths is covered under REST API in the documentation.

The REST path for your app is whatever you have configured it to be. I gave you one example, here’s one more. Once again using the documentation and the basic structure:

<rest-verb> http[s]://<dsp-server-name>/rest/[<service-api-name>]/[<resource-path>][?<param-name>=<param-value>]

Then if you had a service called “weather” and a resource under that called “precipitation” and a parameter called “city” which accepts formats like “Atlanta,Ga” then your REST path would be:

GET http[s]://<dsp-server-name>/rest/weather/precipitation?city=Atlanta,Ga

Of course the path will have to be URL encoded. And the iOS SDK gives multiple examples of constructing this REST path for several services, including a DB and the built-in user service.

1 Like

2015-07-08 20:57:42.009 eMoments[5609:926358] GET CONTENT FROM SERVER
2015-07-08 20:57:43.451 eMoments[5609:926382] Error Error Domain=NSURLErrorDomain Code=-1012 “The operation couldn’t be completed. (NSURLErrorDomain error -1012.)” UserInfo=0x147d6110 {NSErrorFailingURLKey=https://dsp-133829b-49013.cloud.dreamfactory.com/rest/eMomentsServiceAPI/emoments?include_count=1, NSErrorFailingURLStringKey=https://dsp-133829b-49013.cloud.dreamfactory.com/rest/eMomentsServiceAPI/emoments?include_count=1, NSUnderlyingError=0x147f98d0 “The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.)”}

This is my response

Those are not DreamFactory errors, so your app is not returning the error that DreamFactory is returning. Can you try the same call ( https://dsp-133829b-49013.cloud.dreamfactory.com/rest/eMomentsServiceAPI/emoments?include_count=1 ) in a browser or other REST client and let me know the response?

Right now your instance is logging “REST Exception #401 > There is no valid session for the current request.” which may simply mean you are using guest access rather than authenticating. Is your app using guest access or do you require authentication?

All working fine now, my app is able to retrieve data from my remote server. Thanks

Onto my next error~~~

Glad to hear you resolved it! Please post the solution so other readers may benefit.

for (NSDictionary *recordInfo in [responseDict objectForKey:@“record”]) {
TODORecord *newRecord=[[TODORecord alloc]init];
[newRecord setRecord_Id:[recordInfo objectForKey:@“id”]];
[newRecord setRecord_Task:[recordInfo objectForKey:@“name”]];
[newRecord setRecord_Complete:[recordInfo objectForKey:@“complete”]];
[self.todoListContentArray addObject:newRecord];
}

my solution is that the

[responseDict objectForKey:@“record”])
part must say “record”, it wasn’t saying record previously thats why no data could be retrieved.

1 Like