Returning two strings from php to ios - objective-c

I'm creating an app that gets some values from a mysql database via php.
I've gone as far as returning a string that's echoed via php and using it in objective C.
Here's what I have so far:
NSString * strURL = [NSString stringWithFormat:#"http://localhost/search.php?name=%#",name];
NSData * dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString * result = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"%#", result);
Is it possible to return 2 different strings from php and using them separately in xcode or do I have to make 2 different calls to the php file?
Thank you very much for your help!

Great start!
Consider using some structured way to return data from PHP. One easy format that you can learn, which will help with other API integration later, would be JSON.
Apple ships some simple code to to the conversion in iOS5 with NSJSONSerialization
On the PHP side, play around with json_encode. You can pass in an indexed array, for example, which will give you an NSArray on the iOS side.
Some more examples for the iOS side:
How to use NSJSONSerialization

Related

Convert AppleScript response to JSON

I have a Cocoa application, part of it takes AppleScript from the user in a web view. I currently can pass a single string from a command (e.g. the current iTunes song name), however, if I run a command that returns a record (I believe that's what it is based on my research, could be wrong) such as the below I get '(null)' as the stringValue.
tell application "iTunes"
get properties of current track
end tell
If I run this in Script Debugger I can get this as a table shown below, so it's clearly possible.
However, nothing I've tried seems to be working. Based on a number of SO answers I've tried different ways, such as looping over every descriptor index as in this question. However, this doesn't work anymore, as it seems the key is not included in the array.
So, basically, I need to be able to convert an AppleScript output to JSON. I have a serialiser so that's not the issue, as long as I can get them in to Cocoa objects I'm set. What's the best way to do this?
Thanks
Many months late as an answer, but in case you or anyone else cares, here is what I did with a similar problem.
Check out the (sadly defunct) AppScript framework. That combined with lightly modified SBJSON let me convert any AppleScript record into JSON via Cocoa objects.
I used it in JSON Helper which is free on the Mac AppStore. You can also see the source to an earlier version on Google code here, which might be useful if you want to use the modified version of SBJSON.
In my example below the AppleScript record is being supplied via a scripting command.
#implementation makeJSONFromRecord
- (id)performDefaultImplementation {
NSDictionary *asRecord;
NSString *result;
AEMCodecs *codecs = [[AEMCodecs alloc] init];
// Use appscript framework to unpack the event into an object we can use
asRecord =[codecs unpack:[self directParameter]];
[codecs release];
// Use the JSON framework to convert the object to JSON notation
result = [asRecord JSONRepresentation];
if (result==nil) {
//We failed to create any valid JSON so return nothing
NSLog(#"Failed to make JSON from: %#", asRecord);
result=#"";
}
// Return the result to the applescript
return result;
}
#end

How to: standard data in core data on "install"?

I'm working on an application which allows the user to create his own templates with controls. My question here is how I can populate some standard data in my core data database so the user can create his own templates beginning from a standard.
I heard this can be done using local json (there will be a backend using Json to communicate with the frontend), but couldn't find a good tutorial how to do this...
Is there anyone who could help me with this, or is there anyone who has some better ideas to populate this standard data?
I'm using sql script now to populate my data now, but it's not a solution from the moment you install it on an iPad.
Update
I'm willing to create standard entries in my database, so there are some standard controls on the standard template (with template, I mean the controls on a form defined by the user). To be something more specific, how can I parse local json to my core data database?
Yes, JSON is an option.
Simply transfer the JSON into a Foundation object, like this
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *dataArray =
[NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
Now iterate through your new JSON object (an array in this case, but could be a dictionary) and populate your Core Data store one by one with
[NSEntityDescription insertNewObjectForEntityForName:#"Entity"
inManagedObjectContext:self.managedObjectContext];
and save.

Uploading From App to Server in IOS

I know that conventionally for an app to interact with the internet, it must use a web service to exchange information. However, how would one upload data(photos, text, audio recordings etc.etc.) from app to server(which holds data for all user accounts)? I know some people use an email-to-server tactic from research but even then it sounds ineffective and slow. How do apps such as Instagram upload so fast? I am trying to replicate that sort of uploading. Please guide me in the right direction.
Thanks for the help!
You should definitely look into AFNetworking. Here is an example of my uploading an image to a php web service:
NSData *imageData = UIImagePNGRepresentation(pageImage);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://www.SERVER.com"]];
//You can add POST parameteres here
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
author, #"author",
title, #"title",
nil];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"/PATH/TO/WEBSERVICE.php" parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
//This is the image
[formData appendPartWithFileData: imageData name:#"cover_image" fileName:#"temp.png" mimeType:#"image/png"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//Setup Upload block to return progress of file upload
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
float progress = totalBytesWritten / (float)totalBytesExpectedToWrite;
NSLog(#"Upload Percentage: %f %%", progress*100);
}];
//Setup Completeion block to return successful or failure
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
//Code to run after webservice returns success response code
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", [operation error]);
//Code to Run if Failed
}];
[operation start];
Edit- Also I use MBProgressHUD to display to the user the uploading on longer uploads.
As you might know, upload speed is always bound to the speed of the connection type you're using. Even the best upload technique will be slow when the connection is slow (GPRS for example, or EDGE, even 3G can be slow if network coverage is not good).
To upload large sets of data faster/better one thing you could do is compressing the data you're sending using ZIP or any other file compression format you wish or even develop you own compression algorithm (you might not want to do that ;-)).
If you want to reduce the overhead of HTTP/HTTPS connections for example, you can write your very own protocol for data exchange, implement it on the client/server side and upload faster. This will be a lot of work as you have to do all the implementation work not only for the protocol itself as you need to add security etc. But even if you choose to create a protocol, as said in the beginning, it will be slow if the connection is slow.
Update: A presenatation by Mike Krieger (Co-Founder of Instagram) where he covers your question just crossed my way https://speakerdeck.com/u/mikeyk/p/secrets-to-lightning-fast-mobile-design?slide=1.
The reason why you think it's so fast is, that they're updating the UI before the request (the Upload in this case) even completes. This is what Mike describes as "being optimistic". If the request fails you can still notify the user, but in the meantime make him feel productive and act like the request completed successfully.
This is a pretty open ended question but here are a few things to look at:
"Uploading fast" depends on the user's connection and server bandwidth so I won't get into that.
You can upload photos (and other files) by creating NSData objects and attaching them to a POST request. There is already a ton of sample code for uploading NSData but to convert a UIImage you will do the following:
NSData *imageData = UIImagePNGRepresentation(image);
You can do this using the built in Cocoa classes (NSMutableURLRequest) and with 3rd party networking classes (such as AFNetworking - just scroll down to file uploads).
When I send simple data to my webserver, I use the following approach: Use the ASIHttpRequest framework for connecting to your sever. Send the data in HTTP Post body, which is easy to do in the ASIHttpRequest framework. You will want to convert your data to either XML or JSON(use the SBJson framework for this) before sending it. I then write php scripts that parse the json or xml and then input this data into my database with custom SQL scripts. I can give you code snippets if you need them for any of these procedures...
It seems to me that, with your first sentence, you've basically answered your own question.
You need something on your server to receive the files and then you write client code to match. It could be as simple as ftp or as complex as a custom protocol depending on the security and control that you need.

ios read content from private network address

I need to read a file that come for example:
\\192.168.0.1\Folder\Readme.txt
how can I read this file from my app into the iPhone
NSString *pathToTextFile;
NSError *readError;
NSString *fileData = [NSString stringWithContentsOfFile:pathToTextFile
encoding:NSUTF8StringEncoding
error:*readError]
NSLog(#"here is your file as string = %#",fileData);
I think in this case you can use a library like ASIHTTP. Link
It should be possible to download the file into a NSString object, and then store this object into a file.
[nsStringObject writeToFile:pathToFile atomically:YES encoding:stringEncoding error:errorHandler];
As you suggest in your question, you need to access your file over SMB protocol (samba or windows share). I don't think iOS supports smb out of the box, however, i stumbled across tango library on github some time ago. The library claims to be a SMB/CIFS implementation for iOS, so i guess you might give it a try.

Send data from an iPhone to a Web service

I'm developing an iPad application in which a user fills in their details and presses a submit button, which sends the information to a specific Web server (which will later be viewed by a person)
As far as protocols for Web services are concerned, I know JSON and XML. Are there any other protocols that I should be looking into? (or perhaps by a different method completely)
I'd be very grateful for any help.
If you just want to send text info to server you can try this code:
NSString *textdata = [YourTextField text];
NSString *anotherTextdata = [YourAnotherTextField text];
NSString *urlpath;
urlpath = [#"http://yoursiteapiurl.com/" stringByAppendingString:#"yourserverfile.php?textdata="];
urlpath = [urlpath stringByAppendingString:textdata];
urlpath = [urlpath stringByAppendingString:#"&anotherTextData="];
urlpath = [urlpath stringByAppendingString:anotherTextdata];
NSURL *url=[[NSURL alloc] initWithString:[urlpath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *a = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
The variable a will have the response of this URL. The server could send XML and then you can parse that XML using any XML parsing technique.
you can use tbxml for it, its very easy to implement. Follow the link
http://www.tbxml.co.uk/TBXML/TBXML_Free.html
If sending the data over HTTP is an option, I would recommend you look into the excellent ASIHTTPRequest library. As for encoding, I've found the json-framework library to be good.
Use AFNetworking for this.
AFNetworking is smart enough to load and process structured data over the network, as well as plain old HTTP requests. In particular, it supports JSON, XML and Property Lists (plists).