Objective C: Uploading and downloading from a server - objective-c

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

Related

Can I use my remote cloudant(nosqlDB) path for CDTDatastoreManager directory in IBM Bluemix SDK?

I am migrating my application backend from Parse.com to IBM bluemix.
I do not want the CDTDatastore to take control of my persistent store(Core Data) which already exist.
As per the Blue mix Documentation:
NSError *outError = nil;
NSFileManager *fileManager= [NSFileManager defaultManager];
NSURL *documentsDir = [[fileManager URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject];
NSURL *storeURL = [documentsDir URLByAppendingPathComponent:#"cloudant-sync-datastore"];
NSString *path = [storeURL path];
Can I make my "storeURL" to be my remote database URL(https://apikey:apipassword#username.cloudant.com/my_database) i.e Cloudant Database?
I must be in position to create,update,delete,documents in my remote database Directly with out using CDTReplicatorFactory and no offline storage.
Please let me know if further architectural design of my application is required.
This is the pod you should be looking for.
https://cocoapods.org/?q=ObjectiveCloudant
I think no. Please go through their IBM bluemix library. their policy is offline first.
May be create a rest interface with API keys and username given if you want to use core data as persistent store.

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.

Objective C , opening a website without opening it in Safari (for server call purposes)

I am using objective C and I am trying to load a website without opening it in Safari :
I am using the following function :
NSString *website =[NSString stringWithFormat:#"http://www.website.com"];
NSString *connected = [NSString stringWithContentsOfURL:[NSURL URLWithString:website ]encoding:NSStringEncodingConversionAllowLossy error:nil];
but when I check in my database I noticed that it does not load the website , when I load it in the browser it does detect it tho , any reasons ?
thanks
You probably want to use the NSURLConnection class to retrieve data from the network. It will provide a much more useful set of errors, etc.
For simple (but blocking), you can start off with -sendSynchronousRequest:returningResponse:error:, which retrieves a URL from the network giving you the data (in the return value), the HTTP Response, and an error.
NSURL *url = [NSURL URLWithString: #"http://www.website.com"];
NSURLRequest *request = [NSURLRequest requestWithURL: url];
NSURLResponse *response;
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];
If data isn't nil, you've gotten a valid response, otherwise error contains information about the response. You still need to double-check the response in order to make sure you got what you wanted (not a "successful" response that resulted in an error due to the server sending back an error code for HTTP).
In the future, if you need to do a POST command, you can use NSMutableURLRequest and set the type of the request.
Vlad is right, but your code will also only load one file. When you open that file in a browser like Safari, the browser will recursively load all referenced files and will handle any redirect that is present.
UPDATE
In a browser, using the URL without the file name works. I'm not sure you can do that with stringWithContentsOfURL: or with an NSURLConnection.
If the file name is something like "index.html" or whatever it is, try adding that to your URL. These methods load files, so I am betting that you need to provide a fully defined URL, including the file name.

Reading XML File from Server

I'm currently parsing an XML file that resides in my bundle using NSXMLParser with the following line:
NSURL *xmlURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"XMLFileName" ofType:#"xml"]];
But I want to put the same file on my server instead. I can't find an example of how to call the same file from my server. Any help is appreciated.
lq
NSURL has several methods for creating URLs, one of which is -URLWithString:; like so:
NSURL *xmlURL = [NSURL URLWithString:#"http://example.com/example.xml"];
That URL can be passed directly to NSXMLParser; but you might want to do so in a secondary thread.
If you want to HTTP GET the file from your server then you should look at NSURLConnection. It allows you to do synchronous or asynchronous HTTP requests.

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