Sorry for my english ^^
I would know how I can have a result from the google converter tool for currency, available on http://www.google.com/finance/converter?a=1&from=USD&to=GBP for example.
I have already tried something like that :
-(IBAction)getResponse:(id) sender{
NSString *myURLString = #"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";
NSURL *myURL = [NSURL URLWithString: myURLString];
NSData *data = [NSData alloc];
data=[NSData dataWithContentsOfURL:myURL];
if(data!=nil && data != ""){
NSString *response = [[[NSString alloc] initWithData:data]]
[label setText: response];
}
else [label setText:#"not working"];
}
But when I click on my button, the label does not have a text (it is like it is empty).
Am I doing something wrong ?
Is it possible what I want to do ?
Thank you very much for your futures answers !
Olivier.
Yeah.. It is possible...
See the data that you are getting is an HTML file or can be treated as xml. Just parse that xml file and get the result. There ia lot of things in that file but you have to only extract
<div id=currency_converter_result>1 USD = <span class=bld>0.6118 GBP</span>
Hey try this URL
http://www.google.com/ig/calculator?hl=en&q=1USD=?INR
This URL will return the JSON
{lhs: "1 U.S. dollar",rhs: "44.5097254 Indian rupees",error: "",icc: true}
Just parse it. :)
Try...
NSData *data = [[NSData alloc] init];
Then check you've got something in response
NSLog(#"%#", response);
Better yet, remove the NSData alloc/init
Replace with
NSData *data=[NSData dataWithContentsOfURL:myURL];
And, you'll need to parse the return result, because you're not going to get back what you expect. Response will contain HTML page.
You better use an asynchronous request to avoid blocking your app. Easy using ASIHTTPRequest:
- (IBAction)grabURLInBackground:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://www.google.com/finance/converter?a=1&from=USD&to=GBP"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
[label setText: responseString];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error]; //you can log the error description
[label setText:#"not working"];
}
NSString *myURLString = #"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";
NSURL *myURL = [NSURL URLWithString: myURLString];
NSData *data = [NSData alloc];
data=[NSData dataWithContentsOfURL:myURL];
if(data!=nil){
NSString *response = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
NSLog(#"%#",response);
}
Try this.
This API is giving HTML responce.
Related
Alright, so here's where I'm at with my app.
I've got some code that connects to a remote server and grabs some XML data, and forms it into a string. Here is the code below:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSString *accept = [NSString stringWithFormat:#"application/xml"];
[request addValue:accept forHTTPHeaderField: #"Accept"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString* responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"%#",responseString);
Which returns
That's exactly the information I want. My question is how I can get the double value out of the gold brackets and into my application to use.
Thanks a lot!
There are a lot of tutorials of how to use NSXMLParser. For example, ray wenderlich or here and here.
There's quite a few XML parsing options available - ranging from libxml2, to NSXMLParser and a host of open-source projects.
One of my favorite XML parsers is RaptureXML, which can be installed via CocoaPods.
I like to create a category on RXMLElement to parse as follows:
- (PFCurrentConditions*)asCurrentCondition
{
NSString* summary = [[self child:#"weatherDesc"] text];
PFTemperature* temp = [PFTemperature temperatureWithFahrenheitString:[[self child:#"temp_F"] text]];
NSString* humidity = [[self child:#"humidity"] text];
NSString* wind =
[NSString stringWithFormat:#"Wind: %# km %#", [[self child:#"windspeedKmph"] text], [[self child:#"winddir16Point"] text]];
NSString* imageUri = [[self child:#"weatherIconUrl"] text];
return [PFCurrentConditions conditionsWithSummary:summary temperature:temp humidity:humidity wind:wind imageUrl:imageUri];
}
So, you can then use it as follows:
RXMLElement* rootElement = [RXMLElement elementFromXMLData:response.responseData];
__autoreleasing PFWeatherReport* weatherReport = [rootElement asWeatherReport];
Again, this is one of countless options, but my personal favorite.
I need to know the difference between the following two methods of url connection?
What is the significance of these two methods?
Which method is preferred in what circumstances?
Method 1:
file.h
#import
#define kPostURL #"http://localhost/php/register.php"
#define kemail #"email"
#define kpassword #"password"
#interface signup : UIViewController
{
...
...
NSURLConnection *postConnection;
}
#property ...
...
#end
file.m
NSMutableDictionary *input=[[NSMutableDictionary alloc]init];
...
...
...
NSMutableString *postString = [NSMutableString stringWithString:kPostURL];
[postString appendString: [NSString stringWithFormat:#"?%#=%#", kemail, [input objectForKey:#"email"] ]];
[postString appendString: [NSString stringWithFormat:#"&%#=%#", kpassword, [input objectForKey:#"password"] ]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:postString]];
[request setHTTPMethod:#"POST"];
postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
NSLog(#"postconnection: %#", postConnection);
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: postString ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"serverOutput = %#", serverOutput);
Method 2:
NSString *post =[NSString stringWithFormat:#"email=%#&password=%#",[input objectForKey:#"email"], [input objectForKey:#"password"]];
NSString *hostStr = #"http://localhost/frissbee_peeyush/php/login.php?";
hostStr = [hostStr stringByAppendingString:post];
NSLog(#"HostStr %#",hostStr);
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"serverOutput %#", serverOutput);
What if i need to connect to url only using header information ?
Problem: for login and signup, these methods are perfectly fine but whenever i want to insert any string containing special characters such as #,/,_ etc, it is unable to perform any operation.
Guide me plz.
Even the method 1 you have implemented is incomplete as there are many delegates of NSUrlConnection which should be implemented to get the data , handling errors , proxy , authentication etc . It is more advisable to use the first method but not in the way you used.NSUrlConnection in asynchronous in behaviour so You Don't have to wait until the url is loaded.
NSUrlConnection Class Reference
The Second method simply hits the url as sson as it encounters the NSUrl parameter in the NSData . Moreover , you don't have much control over your web service interaction .
NSUrl Class Reference
To get the implementation of NSUrlConnection you can go through the
NSUrlConnection Tutorial
Url With Special Characters:-
[NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
I have a EMR app and i want that i may send the data which i have collected like images and voice to server. in data base so how can i do this . Is there any way to send these data to server through post method.
Here is an example of a HTTP Post request
// define your form fields here:
NSString *content = #"field1=42&field2=Hello";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.example.com/form.php"]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[content dataUsingEncoding:NSISOLatin1StringEncoding]];
// generates an autoreleased NSURLConnection
[NSURLConnection connectionWithRequest:request delegate:self];
Might want to reference http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSURLConnection_Class/Reference/Reference.html
This tutorial is also helpful http://www.raywenderlich.com/2965/how-to-write-an-ios-app-that-uses-a-web-service
In that case, you can do follow two ways:
1. if you strictly like to using POST (i like), u can using cocoahttpserver project:
https://github.com/robbiehanson/CocoaHTTPServer
In iphone app, you can do this code to send POST request:
-(NSDictionary *) getJSONAnswerForFunctionVersionTwo:(NSString *)function
withJSONRequest:(NSMutableDictionary *)request;
{
[self updateUIwithMessage:#"server download is started" withObjectID:nil withLatestMessage:NO error:NO];
NSDictionary *finalResultAlloc = [[NSMutableDictionary alloc] init];
#autoreleasepool {
NSError *error = nil;
NSString *jsonStringForReturn = [request JSONStringWithOptions:JKSerializeOptionNone serializeUnsupportedClassesUsingBlock:nil error:&error];
if (error) NSLog(#"CLIENT CONTROLLER: json decoding error:%# in function:%#",[error localizedDescription],function);
NSData *bodyData = [jsonStringForReturn dataUsingEncoding:NSUTF8StringEncoding];
NSData *dataForBody = [[[NSData alloc] initWithData:bodyData] autorelease];
//NSLog(#"CLIENT CONTROLLER: string lenght is:%# bytes",[NSNumber numberWithUnsignedInteger:[dataForBody length]]);
NSString *functionString = [NSString stringWithFormat:#"/%#",function];
NSURL *urlForRequest = [NSURL URLWithString:functionString relativeToURL:mainServer];
NSMutableURLRequest *requestToServer = [NSMutableURLRequest requestWithURL:urlForRequest];
[requestToServer setHTTPMethod:#"POST"];
[requestToServer setHTTPBody:dataForBody];
[requestToServer setTimeoutInterval:600];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[urlForRequest host]];
NSData *receivedResult = [NSURLConnection sendSynchronousRequest:requestToServer returningResponse:nil error:&error];
if (error) {
NSLog(#"CLIENT CONTROLLER: getJSON answer error download:%#",[error localizedDescription]);
[self updateUIwithMessage:[error localizedDescription] withObjectID:nil withLatestMessage:YES error:NO];
[finalResultAlloc release];
return nil;
}
NSString *answer = [[NSString alloc] initWithData:receivedResult encoding:NSUTF8StringEncoding];
JSONDecoder *jkitDecoder = [JSONDecoder decoder];
NSDictionary *finalResult = [jkitDecoder objectWithUTF8String:(const unsigned char *)[answer UTF8String] length:[answer length] error:&error];
[finalResultAlloc setValuesForKeysWithDictionary:finalResult];
[answer release];
[self updateUIwithMessage:#"server download is finished" withObjectID:nil withLatestMessage:NO error:NO];
if (error) NSLog(#"CLIENT CONTROLLER: getJSON answer failed to decode answer with error:%#",[error localizedDescription]);
}
NSDictionary *finalResultToReturn = [NSDictionary dictionaryWithDictionary:finalResultAlloc];
[finalResultAlloc release];
return finalResultToReturn;
}
Don't forget to pack attributes with images to base64.
Finally, if u don't like to keep data, which u send in you mac app, u can send to u database using any database C api. I recommend to using core data to save receive data.
How can I post a string(i.e) a word to web server url in iphone sdk?
Some sample codes or tutorials would be appreciated.
Thanking you.
This may help you, although I havent tested it:
NSMutableString *httpBodyString;
NSURL *url;
NSMutableString *urlString;
httpBodyString=[[NSMutableString alloc] initWithString:#"Name=The Big Bopper&Subject=Hello Baby&MsgBody=...You knooow what I like...Chantilly lace..."];
urlString=[[NSMutableString alloc] initWithString:#"http://www.somedomain.com/contactform.php"];
url=[[NSURL alloc] initWithString:urlString];
[urlString release];
NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
[url release];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[httpBodyString dataUsingEncoding:NSISOLatin1StringEncoding]];
[httpBodyString release];
NSURLConnection *connectionResponse = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if (!connectionResponse)
{
NSLog(#"Failed to submit request");
}
else
{
NSLog(#"--------- Request submitted ---------");
NSLog(#"connection: %# method: %#, encoded body: %#, body: %a", connectionResponse, [urlRequest HTTPMethod], [urlRequest HTTPBody], httpBodyString);
NSLog(#"New connection retain count: %d", [connectionResponse retainCount]);
responseData=[[NSMutableData data] retain];
NSLog(#"response", responseData);
}
Source: http://www.iphonedevsdk.com/forum/iphone-sdk-development/6341-help-executing-http-url-post-variables.html
You can post the string to webservice in so many ways, In those one is
Using Rest protocol:
It has two sub types, HTTP GET, HTTP POST. The Http Get is simple.
You can add the value to the attribute and you can directly call the service.
Check the following code.
NSString *url = #"http://123.456.789.0?action=get_movies";
Here the I am passing the get_movies string to the server to the action attribute.
and then follow the code for requesting to server.
NSURL *reqUrl = [[NSURL alloc] initWithString:url];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:reqUrl];
NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSStringEncoding responseEncoding = NSUTF8StringEncoding;
if ([response textEncodingName]) {
CFStringEncoding cfStringEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)[response textEncodingName]);
if (cfStringEncoding != kCFStringEncodingInvalidId) {
responseEncoding = CFStringConvertEncodingToNSStringEncoding(cfStringEncoding);
}
}
[reqUrl release];
NSString *dataString = [[NSString alloc] initWithData:data encoding:responseEncoding];
the dataString is the responseString from the server. You can use that.
Regards,
Satya.
Is it possible to upload video to a server? I know that images are possible.
If someone can just point me in the right direction that would be awesome.
Thanks
Edited Aug 2015
This answer is now seriously out of date. At the time of writing there weren't to many options and videos were relatively small in size.
If you are looking at doing this now, I would use AFNetworking which makes this much simpler. It will stream the upload from file rather than holding it all in memory, and also supports the new Apple background upload Task.
Docs here: https://github.com/AFNetworking/AFNetworking#creating-an-upload-task
--
Yes this is possible and this is how i went about it.
Implement the following function which runs when the media picker is finished.
- (NSData *)generatePostDataForData:(NSData *)uploadData
{
// Generate the post header:
NSString *post = [NSString stringWithCString:"--AaB03x\r\nContent-Disposition: form-data; name=\"upload[file]\"; filename=\"somefile\"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\n" encoding:NSASCIIStringEncoding];
// Get the post header int ASCII format:
NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Generate the mutable data variable:
NSMutableData *postData = [[NSMutableData alloc] initWithLength:[postHeaderData length] ];
[postData setData:postHeaderData];
// Add the image:
[postData appendData: uploadData];
// Add the closing boundry:
[postData appendData: [#"\r\n--AaB03x--" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
// Return the post data:
return postData;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//assign the mediatype to a string
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
//check the media type string so we can determine if its a video
if ([mediaType isEqualToString:#"public.movie"]){
NSLog(#"got a movie");
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *webData = [NSData dataWithContentsOfURL:videoURL];
[self post:webData];
[webData release];
}
for the post function i had something like this which i got from somewhere else (sorry i dont know where i found it):
- (void)post:(NSData *)fileData
{
NSLog(#"POSTING");
// Generate the postdata:
NSData *postData = [self generatePostDataForData: fileData];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Setup the request:
NSMutableURLRequest *uploadRequest = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.example.com:3000/"] cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval: 30 ] autorelease];
[uploadRequest setHTTPMethod:#"POST"];
[uploadRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[uploadRequest setValue:#"multipart/form-data; boundary=AaB03x" forHTTPHeaderField:#"Content-Type"];
[uploadRequest setHTTPBody:postData];
// Execute the reqest:
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:uploadRequest delegate:self];
if (conn)
{
// Connection succeeded (even if a 404 or other non-200 range was returned).
NSLog(#"sucess");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Got Server Response" message:#"Success" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
// Connection failed (cannot reach server).
NSLog(#"fail");
}
}
The above snippet builds the http post request and submits it. You will need to modify it if you want decent error handling and consider using a library that allows async upload (theres one on github)
Also Notice the port :3000 on the server url above, I found it easy for bug testing to start a rails server on its default port 3000 in development mode so i could see the request parameters for debugging purposes
Hope this helps
Since iOS8 there is no need to use 3rd party libraries and you can stream video directly from the file which solves crucial OUT OF MEMORY ERROR when you try to upload bigger videos while loading them from file:
// If video was returned by UIImagePicker ...
NSURL *videoUrl = [_videoDictionary objectForKey:UIImagePickerControllerMediaURL];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:VIDEO_UPLOAD_LINK]];
[request addValue:#"video" forHTTPHeaderField: #"Content-Type"];
[request setHTTPMethod:#"POST"];
NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath:[videoUrl path]];
[request setHTTPBodyStream:inputStream];
self.uploadConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
iOS7 also offers great NSURLSeession / NSURLSessionUploadTask combo solution, which not only let's you stream directly from the file, but can also delegate task to the iOS process, which will let upload to finish even when your app is closed.
It requires a bit more coding and I have no time to write it all here (you can Google it).
Here are the most crucial parts:
Confugure audio session in background support:
-(NSURLSession *)urlSession{
if (!_urlSession) {
NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
NSString *bundleId = infoDict[#"CFBundleIdentifier"];
NSString *label = [NSString stringWithFormat:#"ATLoggerUploadManager_%#", bundleId];
NSURLSessionConfiguration *conf = (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) ? [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:label] : [NSURLSessionConfiguration backgroundSessionConfiguration:label];
conf.allowsCellularAccess = NO;
_urlSession = [NSURLSession sessionWithConfiguration:conf delegate:self delegateQueue:self.urlSessionQueue];
_urlSession.sessionDescription = #"Upload log files";
}
return _urlSession;
}
Upload task method:
-(NSURLSessionUploadTask *)uploadTaskForFilePath:(NSString *)filePath session:(NSURLSession *)session{
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
// Consruct request:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
NSString *finalUrlString = [self.uploadURL absoluteString];
if (self.uploadUserId) {
[request setValue:self.uploadUserId forHTTPHeaderField:#"X-User-Id"];
finalUrlString = [finalUrlString stringByAppendingFormat:#"?id=%#", self.uploadUserId];
}
[request setURL:[NSURL URLWithString:finalUrlString]];
/*
It looks like this (it only works if you quote the filename):
Content-Disposition: attachment; filename="fname.ext"
*/
NSString *cdh = [NSString stringWithFormat:#"attachment; filename=\"%#\"", [filePath lastPathComponent]];
[request setValue:cdh forHTTPHeaderField:#"Content-Disposition"];
error = nil;
unsigned long fileSize = [[fm attributesOfItemAtPath:filePath error:&error] fileSize];
if (!error) {
NSString *sizeInBytesAsString = [NSString stringWithFormat:#"%lu", fileSize];
[request setValue:sizeInBytesAsString forHTTPHeaderField:#"X-Content-Length"];
}
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:fileUrl];
uploadTask.taskDescription = filePath;
return uploadTask;
}
Upload function:
[self.urlSession getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
NSMutableDictionary *tasks = [NSMutableDictionary new];
int resumed_running_count = 0;
int resumed_not_running_count = 0;
int new_count = 0;
// 1/2. Resume scheduled tasks:
for(NSURLSessionUploadTask *task in uploadTasks) {
//MILogInfo(#"Restored upload task %zu for %#", (unsigned long)task.taskIdentifier, task.originalRequest.URL);
if (task.taskDescription) {
[tasks setObject:task forKey:task.taskDescription];
}
BOOL isRunning = (task.state == NSURLSessionTaskStateRunning);
if (!isRunning) {
resumed_not_running_count++;
}else{
resumed_running_count++;
}
[task resume];
}
// 2/2. Add tasks / files not scheduled yet:
NSString *uploadFilePath = nil;
// already uploading:
if (![tasks valueForKey:uploadFilePath]) {
NSURLSessionUploadTask *uploadTask = [self uploadTaskForFilePath:uploadFilePath session:_urlSession];
new_count++;
[uploadTask resume];
}
}];
Background session requires UIApplecation delegate (AppDelegate callback implemented:
(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
{
NSLog(#"Background URL session needs events handled: %#", identifier);
completionHandler();
}
Have a look at the UIImagePickerController.
As of 3.0 you can allow the choose to shoot a video or pick an existing video. According to the docs you're limited to 10min max on the movie though:
http://developer.apple.com/IPhone/library/documentation/UIKit/Reference/UIImagePickerController_Class/UIImagePickerController/UIImagePickerController.html
NSURL *urlvideo = [info objectForKey:UIImagePickerControllerMediaURL];
NSString *urlString=[urlvideo path];
NSLog(#"urlString=%#",urlString);
NSString *str = [NSString stringWithFormat:#"you url of server"];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setFile:urlString forKey:#"key foruploadingFile"];
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request startSynchronous];
NSLog(#"responseStatusCode %i",[request responseStatusCode]);
NSLog(#"responseStatusCode %#",[request responseString]);