I have a back end set up with python functions. I want python to do a lot of location based work instead of have objective-c do the computations and everything else. There are reasons for this.
However, I have no idea how to connect to the server and call the python functions from objective-c. Does anyone开发者_高级运维 have any knowledge of this?
Thanks!
I, too, am using Python on a server (Google App Engine) for one of my projects. I have an endpoint that returns a bunch of data in JSON format. (parseJSON
is my own method)
@interface GSData : NSObject {
NSMutableData *responseData;
}
/////////////////////////
// in my .m file
- (void)getData {
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:DATA_URL]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Connection failed: %@", [error description]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
[self parseJSON:responseString];
[responseString release];
}
For JSON, I'm using this project.
Hope this helps!
There are a few things to consider here.
First of all, according to the Apple HIG guidelines, your app needs to check for network connectivity, using the Reachability class.
To execute Python, you probably want to create endpoints on the server (web pages that interact with Python and your app).
For the actual requests, I would recommend using the ASIHTTPRequest class. It does a lot of work for you (including the required connectivity checks).
EDIT
As per the OP's request, here is a psuedo example.
Have a web service running. Lets pretend there is a Python script called "Geo.py" that returns a latitude, based on a location. (Also known as reverse geocoding.)
Use ASIHTTPRequest to send a request to `http://yourserver.com/Geo.py. You can send the requests asynchronously or synchronously.
That should be it. ASIHTTPRequest should handle error checking and connectivity for you.
精彩评论