Call function on server from iOS app - Goal C

If you are familiar with the Parse.com Javascript SDK, this is what I am trying to do for my own server for my iOS application (Objective-c). I want to be able to send some string of a function that is on my server, start the server of my function, and then return the string to the application or some XML or JSON data.

Is it possible?

I am new to doing something like this when the application makes a call to the server. I studied opening a port on my server, but couldn't find a way to get the data back to the iOS app. (I found this lib, but its for OS X https://github.com/armadsen/ORSSerialPort ). Also, I'm not sure that I have a function that works with an open port on the server. So how can I configure it so that I can call my server and run the function?

Any help would be greatly appreciated.

+4
source share
1 answer

You just need the POST data to your server.

The port can be anything you want.

Submit your script with the domain URL to publicly publish the network request.

You can try this function:

-(NSData *)post:(NSString *)postString url:(NSString*)urlString{

    //Response data object
    NSData *returnData = [[NSData alloc]init];

    //Build the Request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[postString length]] forHTTPHeaderField:@"Content-length"];
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

    //Send the Request
    returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];

    //Get the Result of Request
    NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];

    bool debug = YES;

    if (debug && response) {
        NSLog(@"Response >>>> %@",response);
    }


    return returnData;
}

And here is how you use it:

NSString *postString = [NSString stringWithFormat:@"param=%@",param];
NSString *urlString = @"https://www.yourapi.com/yourscript.py";

NSData *returnData =  [self post:postString url:urlString];

PHP

<?php
$response=array();
if(isset($_POST['param'])){
  $response['success'] = true;
  $response['message'] = 'received param = '.$_POST['param'];
}else{
  $response['success'] = false;
  $response['message'] = 'did not receive param';
}
$json = json_encode($response);
echo $json;
+2

All Articles