Objective C , opening a website without opening it in Safari - objective-c

I am trying to find a way to load a website (for server call purposes) but I don t want it to open neither in safari nor in a UIWebView . I usually use this code for opening in safari
[[UIApplication sharedApplication]
openURL:[NSURL URLWithString:#"http://www.google.com"]];
and for the UIWebViews
[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:thelink]]];
I tried to use the UIWebView without actually having a physical one but the page didn't load (I know that because the server call were not made at all)
thanks

You should use NSURLRequest, for example:
NSString * url = #"http://myapi.mysite.com/api.php";
NSMutableURLRequest * aRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
NSHTTPURLResponse * httpResponse = nil;
NSError * urlError = nil;
NSData * responseData = [NSURLConnection sendSynchronousRequest:aRequest returningResponse:&httpResponse error:&urlError];
Where responseData is the body of the response, you can use httpResponse to check status codes etc...

NSURLConnection is your friend:
NSURL *URL = [NSURL URLWithString:#"http://www.google.com"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:URL];
// configure req to have post data and such
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
// do something with data

Just use
NSString *connected = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.google.com"] encoding:NSStringEncodingConversionAllowLossy error:nil];
if connected is != NULL then everything worked fine

Related

Objective-C send get method with header to download file

in my osx app, I want to download a file from a website, in order to do that, I first tried with NSData dataWithContentsOfURL:url but I'm accessing ot throught an API, so I need to send a token in the header of my GET request so now, my method to download a file is that:
-(void)downloadFile:(NSString*)name from:(NSString*)stringURL in:(NSString*)path{
NSURL *aUrl = [NSURL URLWithString:stringURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"GET"];
[request addValue:self.token forHTTPHeaderField:#"Authorization"];
NSLog(#"%#", stringURL);
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
if ( data )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#.torrent", path,name];
[data writeToFile:filePath atomically:YES];
}
}
The url loged is the good one. But the data variable is nil and the error one contain an NSURLErrorDomaincode with the code 1002. Referring to the doc:
Returned when a properly formed URL cannot be handled by the framework.
The most likely cause is that there is no available protocol handler for the URL.
So how can I send a GET request with custom headers and then download the file ?
There are some mistakes in your code:
documentsDirectory is not used, so the data can be wrote to nowhere.
The default HTTP method is GET so you do not need to specify it.
You should pass in the full URL: http://api.t411.io/torrents/download/4693572. And I thought you may passed in api.t411.io/torrents/download/4693572 before.
And I recommend you using the NSURLSession API that Apple brings in iOS 7 and OS X v10.9.
// in viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
_config = [NSURLSessionConfiguration defaultSessionConfiguration];
_config.HTTPAdditionalHeaders = #{#"Authorization": self.token};
_session = [NSURLSession sessionWithConfiguration:_config];
}
- (void)downloadFile:(NSString*)name from:(NSString*)stringURL in:(NSString*)path {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLSessionDataTask *task = [_session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
return;
}
if (data) {
// Your file writing code here
NSLog(#"%#", data);
}
}];
[task resume];
}

Obj-C NSURLConnection not working

So i am trying to send data to a webservice via url with a parameter. the code i have is below but it never hits the server. the request and responses are null. What am i doing wrong?
-(void) postData:(NSString *)data{
NSURLResponse* response;
NSError* error = nil;
NSString *urlString = [NSString stringWithFormat:#"http://someaddress.com/api?data=%#", data];
NSURL *lookupURL = [NSURL URLWithString:urlString];
//Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:lookupURL];
NSData *request = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *dataString = [[NSString alloc] initWithData:request encoding:NSUTF8StringEncoding];
NSLog(#"-----------------------------");
NSLog(#"Request: %#", theRequest);
NSLog(#"req response: %#", request);
NSLog(#"response: %#", dataString);}
you want to POST some binary data but you do a GET request and try to put the binary into the url. (without encoding it)
sample post:
NSURL *url = [NSURL URLWithString:#"http://server.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = #"POST";
request.HTTPBody = postData;
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
also, note that the synchronous get is bad as it blocks :) use async networking!

load pages in UIWebview

I am trying to display web pages using UIwebview on iPad.
I used following code :-
NSString *urlAddress=#"http://google.com";
NSURL *url = [NSURL URLWithString:urlAddress];
NSLog(#"The value of url in screen 2 is %#",url);
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[web loadRequest:requestObj];
web is an object of type uiwebview .
This works fine with certain links but when i tried to open below link
http://deverpids.ltisap.com:8000/sap(bD1lbiZjPTgwMA==)/bc/bsp/sap/zbbdashboard/demo.htm#infohttp://deverpids.ltisap.com:8000/sap(bD1lbiZjPTgwMA==)/bc/bsp/sap/zbbdashboard/demo.htm#info
It does not display anything .Read few articles and taught this could be related to a proxy issue
How to deal with proxy setting in UIWebView?
so tried to use this but no success . code used is as below :
NSURL *url = [NSURL URLWithString:#"http://google.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
NSLog(#"error is %#",response);
}
But now nothing loads up in webview .how do i tackle this .

ASIHTTPRequest and NSURLRequest different result

I send request to some url with ASIHTTPRequest, and always get strange response with different HTML body. If i make same request from browser or from NSURLRequest class, i get correct response with correct HTML body.
//Here is code of NSURLRequest. I'm getting correct response;
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *resp = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest: request returningResponse: &resp error: &err];
NSString *theString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"%#",theString);
//Here is code of ASIHTTPRequest. I'm getting different response. The html body is shorter than original and different;
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
NSString *responseString = [request responseString];
}];
[request startAsynchronous];
I also tryed to send simple synchronous request with ASIHTTPRequest, but result the same. What it could be?
may be server have different logic for different request header

What's the equivlent code for stringWithContentsOfURL using a NSURLRequest?

NSURL *url = [NSURL URLWithString:escapedUrlString];
NSString *responseString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
But, I was reading online that I should probably be using an NSURLRequest instead if I want to add a timeout. The first code works fine, but the second code always returns #"" (not nil, just ""). Anyone have any suggestions?
I also read that the NSURLConnection takes care of any sort of web compression that might be done whereas NSURLRequest won't handle that, so I thought I better just go for the more well rounded solution.
http://lists.apple.com/archives/cocoa-dev/2009/Oct/msg01921.html
NSString *escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *responseString;
NSURLResponse *response;
NSError *error;
NSURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL URLWithString:escapedUrlString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:5]; // 5 second timeout?
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]){
NSLog(#"Recieved String Result: %#", responseString);
} else {
NSLog(#"Response String is null!");
}
Thanks for the good suggestions. The code magically worked this morning, so I'm guessing my webserver went down or something last night.