How to get text file from the URL objective c? - objective-c

Currently I'm working on translate application , I referred from read text file returned by URL to get the translated text file
https://translate.google.com.tw/translate_a/t?client=t&hl=en&sl=" +
sl + "&tl=" + tl + "&ie=UTF-8&oe=UTF-8&multires=1&oc=1&otf=2&ssel=0&tsel=0&sc=1&q="
.This is works fine in android while translate, but in iOS it returns text as
The below code I used to get the file
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://translate.google.com.tw/translate_a/t?client=t&hl=en&sl=en&tl=ta&ie=UTF-8&oe=UTF-8&multires=1&oc=1&otf=2&ssel=0&tsel=0&sc=1&q=summer"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
connectionRequest=[[NSURLConnection alloc]initWithRequest:request delegate:self];
NSString* newStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"newStr%#",newStr);
What I'm doing?please anybody help me to get out of this..Thanks

I recommend using web service rest of google. Can read the official guide.
enter link description here

NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://translate.google.com.tw/translate_a/t?client=t&hl=en&sl=en&tl=ta&ie=UTF-8&oe=UTF-8&multires=1&oc=1&otf=2&ssel=0&tsel=0&sc=1&q=summer"]];
[request setHTTPMethod:#"GET"];
[self addHeaders:request];
[NSURLConnection connectionWithRequest:request delegate:self];
[pool release];
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
NSString* newStr = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
}

Related

How to send Array of objects to JSON?

I am hitting a web service with array of objects. But in server side they are getting only null value for all the fields.
Client side code is:
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:urlRequest
delegate:self];
//************DATA formation
NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc]init];
NSMutableDictionary *jsonDict1 = [[NSMutableDictionary alloc]init];
[jsonDict setObject:#"3" forKey:#"rollNo"];
[jsonDict setObject:#"Ezhil" forKey:#"FirstName"];
[jsonDict setObject:#"Arasu" forKey:#"LastName"];
[jsonDict1 setObject:#"4" forKey:#"rollNo"];
[jsonDict1 setObject:#"XYZ" forKey:#"FirstName"];
[jsonDict1 setObject:#"ABC" forKey:#"LastName"];
NSArray *jsonArray=[[NSArray alloc]initWithObjects:jsonDict,jsonDict1, nil];
//Converting to JSON string.
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSString *jsonString = [writer stringWithObject:jsonArray];
NSLog(#"JSON String : %#",jsonString);
//************Setting DATA in URL
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[connection start];
// Code for response....
I dont know were i went wrong. Can any one help me for this issue.
Thanks in advance.
I'd scrap the SBJson stuff and just use the native controls...
Do everything the same as you are doing but remove the SBJsonWriter stuff and do this to set the body of the request...
[urlRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONWritingPrettyPrinted error:&error]];
That should work.
Thank you.. Application is working fine without any modification. The problem is with server side. But i think we can go with your suggestion instead of using external framework.
In both the case I am getting the json object like this,
JSON String :
[{"rollNo":"3","FirstName":"Ezhil","LastName":"Arasu"},
{"rollNo":"4","FirstName":"XYZ","LastName":"ABC"}]

Pause and Resume downloads in Objective-C

Everything seems to work well except the pause/resume functionality. My issue is that when a download tries to continue from where it left off,set the header range but not work properly. When I download zip file and extract it,extracted file extension is download.zip.cpgz. Please fix my issue.
My code:
**UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:#"navigator.userAgent"];
NSLog(#"user aggent %#",secretAgent);
if([[NSFileManager defaultManager] fileExistsAtPath:_path]){
NSDictionary *fileDictionary = [[NSFileManager defaultManager] fileAttributesAtPath:_path traverseLink:YES];
unsigned long long int h = [fileDictionary fileSize];
_textField.text = self.textField.text;
//[self performSelectorInBackground:#selector(downloadZipfile) withObject:nil];
// NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:_textField.text]
//
// cachePolicy:NSURLRequestUseProtocolCachePolicy
//
// timeoutInterval:60.0];
//NSFileSize *fileSize = [NSFileSize]
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.textField.text]];
NSString *range = #"bytes=";
range = [range stringByAppendingString:[[NSNumber numberWithInt:h] stringValue]];
range = [range stringByAppendingString:#"-"];
[request setHTTPMethod:#"GET"];
[request setValue:#"keep-live" forHTTPHeaderField:#"Connection"];
[request setValue:range forHTTPHeaderField:#"Keep-Alive"];
[request setValue:secretAgent forHTTPHeaderField:#"User-Agent"];
[request setValue:range forHTTPHeaderField:#"Range"];
NSLog(#"range set %#",range);
// create the connection with the request
// and start loading the data
_downloadConeection=[[NSURLConnection alloc] initWithRequest:request delegate:self];**

breaking up an API connection call into functions Objective-C

This most likely a very trivial questions but I have a connection set up to an API in order to retrieve information. Right now I have everything setup in viewDidLoad. I know there is a more efficient way to place this information for later access by the user but I am too inexperienced in Objective-C to know how to do it. Here is how I have it all laid out at the moment.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:#"https://www.myurl.com"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSData *myResponse = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
NSString *myString = [[NSString alloc] initWithData:myResponse encoding:NSUTF8StringEncoding];
SBJsonParser *myParser = [[SBJsonParser alloc] init];
NSArray *myData = [parser objectWithString:myString error:nil];
Try this:
- (void)loadAndParseURL:(NSString *)URLString
completion:(void (^)(NSArray *data))completion {
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:URLString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
dispatch_async(dispatch_get_global_queue(DISPATH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *myResponse = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
NSString *myString = [[NSString alloc] initWithData:myResponse encoding:NSUTF8StringEncoding];
SBJsonParser *myParser = [[SBJsonParser alloc] init];
NSArray *myData = [parser objectWithString:myString error:nil];
completion(myData);
});
}
completion is a block (anonymous function pointer), which accepts an array as parameter and executes customized code blocks. The block holds the value of local variables, aka the 'environment', and evaluates its content at the time of execution(, usually with delay of some kind), in this example, after myData is parsed from myString. dispatch_async puts the anonymous block that sends the request and does other stuff onto a background queue (in a background thread, of course). So the calling to this method is returned before the response is even received, and you should arrange anything after within the completion block.
If spinning it off into a thread is what you are looking for I would use sendAsynchronousRequest
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
SBJsonParser *myParser = [[SBJsonParser alloc] init];
NSArray *myData = [parser objectWithString:myString error:nil];
// Do what you want with the response and subscribe
//anywhere in your code to get notified when it completed.
[[NSNotificationCenter defaultCenter]
postNotificationName:#"NotifyMeWhenDone"
object:self];
}];

IOS Application to send data to a Rest API service

I want to create an iPhone application to send data to a Rest API service. If the data is a string defined as geoX#35#geoY#65 which NSS method shall i use. Was thinking of NSString and NSMutablerequest to make my request and define my string but this isn't working atm.Also i am using NSURLconnection to establish a connection with the server(maybe that's faulty too). Anyone that can help ?
Thanks in advance.
Your connection data is using special characters and if you try to do this with GET method of NSURLConnection. It will Shows connection error. For this You have to use POST method like :
NSData *body = nil;
NSString *contentType = #"text/html; charset=utf-8";
NSURL *finalURL = #"YOUR URL WITH the ?input=";
NSString *yourString = #"geoX#35#geoY#65";
contentType = #"application/x-www-form-urlencoded; charset=utf-8";
body = [[NSString stringWithFormat:#"%#", yourString] dataUsingEncoding:NSUTF8StringEncoding];
if (nil==finalURL) {
finalURL = url;
}
NSMutableDictionary* headers = [[[NSMutableDictionary alloc] init] autorelease];
[headers setValue:contentType forKey:#"Content-Type"];
[headers setValue:mimeType forKey:#"Accept"];
[headers setValue:#"no-cache" forKey:#"Cache-Control"];
[headers setValue:#"no-cache" forKey:#"Pragma"];
[headers setValue:#"close" forKey:#"Connection"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:body];
self.conn = [NSURLConnection connectionWithRequest:request delegate:self];

Facing An Issue to share a message using LinkedIn API in my Iphone Application

i am developing an iphone app, In that app i am using LinkedIn Integration For Updating My status...But I'am unable to Update My Status..Any Help will be Appreciated.
Thanks In Advance
Pandu1251
- (IBAction)postButton_TouchUp:(UIButton *)sender
{
[statusTextView resignFirstResponder];
NSURL *url = [NSURL URLWithString:#"http://api.linkedin.com/v1/people/~/shares"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
consumer:oAuthLoginView.consumer
token:oAuthLoginView.accessToken
callback:NO
signatureProvider:nil];
NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:
[[NSDictionary alloc]
initWithObjectsAndKeys:
#"anyone",#"code",nil], #"visibility",
statusTextView.text, #"comment", nil];
NSLog(#"statusTextView.text is---%#",statusTextView.text);
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSString *updateString = [update JSONString];
NSLog(#"updateString is---%#",updateString);
[request setHTTPMethod:#"POST"];
[request prepare];
[request setHTTPBodyWithString:updateString];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(postUpdateApiCallResult:didFinish:)
didFailSelector:#selector(postUpdateApiCallResult:didFail:)];
[request release];
}
first you have to check for the parameters like consumer and access token etc.
or you can test it in console
https://apigee.com/console/linkedin
Have you seen this: http://www.whitneyland.com/2011/03/iphone-oauth.html
or this:
https://github.com/ResultsDirect/LinkedIn-iPhone
They should help you get started on iOS