Sending data to PHP scripts in the background from Cocoa
I have information I'm planning to sync between an iPhone application and a desktop application via a PHP script; is there a method of calling the script in the background 开发者_JAVA技巧to send data to the online database and then retrieve the data from the script?
These people are all contrary a**holes. If you don't like his question, SHUT UP. I loathe all the know-it-all poo-pooers around here, who literally dont care what YOU are asking.. they'll just try to dissuade you from whatever that stupid thing was that you were thinking, and that you should do this instead.. uh, why? because you dont know how do it? Long story short, there are HUDREDS of ways to do this… here's one I wrote / like… but as i said, the only reason this problem is a bit confouding is because there are TOO many ways to do it...
#import "NSData+Base64.h" //i'm sending an image, so i base64 encode it.
- (NSArray *)makeObjectFromJSONviaPHPwithThis:(NSData *)data
{
NSTask *phpTask = [NSTask new];
[php setStandardOutput:pipe]; [php setLaunchPath:@"/usr/bin/php"];
[php setArguments:[NSArray arrayWithObjects:
@"-f", //runs your bundled script via cli
[[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:@"bundledScript.php"],
[data base64EncodedString], nil]];
NSPipe *pipe = [NSPipe new];
NSFileHandle *handle = [pipe fileHandleForReading];
[php launch];
NSString *results = [[NSString alloc] initWithData:
[handle readDataToEndOfFile] encoding:NSASCIIStringEncoding];
//"results" has your response from php….. I sent them back as * seperated string.
//Now i split the strings and shove them into an array!
return NSArray *parsedResults = [results componentsSeparatedByString:@"*"];
}
You could just make it a web app instead of a native app
See the URL Loading System and NSURLConnection. The "Related Sample code" on the NSURLConnection link may be helpful
If you wrap up all of your functions in a nice little class, you can use a method within the SDK to call a method in a separate thread. the method is called detachNewThreadSelector:toTarget:withObject:
Note if you don't want to do any processing of the returned data, than you can ignore this, and just use the standard approach to URL loading, as it is Asynchronous, and makes the connection in the background anyway, however the difference is that it's callback is called on the main thread (AFAIK). By executing in a separate thread, everything will be done there, so the UI will be free.
Also take care, the world of multi-threading can be long and rocky. Good luck
精彩评论