Send data from an iPhone to a Web service - objective-c

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).

Related

Returning two strings from php to ios

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

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.

Cocoa HTTP PUT with content-range

Is it possible to use an NSURLConnection/NSURLRequest combination to send a PUT request to a server with a Content-Range header? By that I mean I want to resume an upload to the server which can accept a byte range in the request to resume the upload.
I see you can set an NSInputStream as the request body so I figured that I could subclass that and override the the open/seek functions and set the request header but it seems to call on undocumented selectors and break the implementation.
I'm sure I could do this with CFNetwork but it just seems like there must be a way to do it with the higher level APIs.
Any ideas on where to start?
EDIT:
To answer my own question, this is indeed possible after reading a blog [http://bjhomer.blogspot.com/2011/04/subclassing-nsinputstream.html] which details the undocumented callbacks which relate to CFStream. Once those are implemented I can call the following in the open callback to skip ahead:
CFReadStreamSetProperty((CFReadStreamRef)parentStream, kCFStreamPropertyFileCurrentOffset, (CFNumberRef)[NSNumber numberWithUnsignedLongLong:streamOffset]);
Thanks,
J
I think the server needs to supports put method combines with range but this will be the way to do it with high level Objective-C API
NSURL *URL = [NSURL URLWithString:strURL];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:URL];
NSString *range = [NSString stringWithFormat:#"bytes=%lld-%lld",bytesUploaded,uploadSize];
[urlRequest addValue:range forHTTPHeaderField:#"Range"];
[urlRequest setHTTPMethod:#"PUT"];
self.connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
Cheers
First, if you want to do fancy work with HTTP, I typically recommend ASIHTTPRequest. It's solid stuff that simplifies a lot of more complicated HTTP problems. It's not really needed for setting a simple header, but if you're starting to build something more complex, it can be nice to move over to ASI sooner rather than later.
With an NSMutableURLRequest, you can set any header you want using addValue:forHTTPHeaderField:. You can use that to set your Content-Range.
Like I posted in my comment, you can facilitate what you want without dropping down to the CoreFoundation level:
As NSInputStream inherits NSStream, it is possible to prepare the stream as follows:
NSNumber *streamOffset = [NSNumber numberWithUnsignedInteger:lastOffset];
[inputStream setProperty:streamOffset forKey: NSStreamFileCurrentOffsetKey];
(Assuming lastOffset is an NSUInteger representation of your last file offset in bytes and inputStream is the stream you want to set as the request's HTTPBodyStream.)

Objective C: Uploading and downloading from a server

What's the easiest way to retrieve text and upload text to a server? And how would I create files from the app on the server?
the easiest way to read text from an http endpoint on a web server is:
NSURL *url = [NSURL URLWithString:#"http://www.apple.com"];
NSString *content = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding];
to save text, i would use a simple rest based xml web service where i would post the text data to this service and read the appropriate response back to know if the operation was successful

What's the right way to base64 Encoding in Cococa?

I'm enconding this data with this line:
NSString *authString = [[[NSString stringWithFormat:#"%#:%#", email, password] dataUsingEncoding:NSUTF8StringEncoding] base64Encoding];
for a basic HTTP Authentication
It works quite perfect but i'm getting this warning:
warning: 'NSData' may not respond to '-base64Encoding'
is there other way for encoding or how do i remove this warning?
The warning is correct: NSData does not respond to that message. As you can see in the documentation, NSData does not implement base-64 encoding and decoding.
You'll need to either use OpenSSL's BIO API to do the job, or use a third-party framework or library that wraps that (or a separate encoder/decoder) in an easy Cocoa API. A Google search for “Cocoa Base64” will turn up some options.