This question already has answers here:
URL Validation (Objective-C)
(4 answers)
Closed 9 years ago.
I want to find that whether the URL im giving is valid or not, and whether it exists in internet or not..
Is there any way to do that using objective-C?
You can see if a URL is valid or not by doing the following:
NSString *urlString = ... // some URL to check
NSURL *url = [NSURL URLWithString:urlString];
if (url) {
// valid URL (meaning it is the proper format)
}
To see if the URL exists in the Internet, you need to perform a HEAD request and check the result. This is more efficient than loading all of the data for the URL.
NSMutableURLRequest request = [NSMutableURLRequest requestWithURL:inURL];
[request setHTTPMethod:#"HEAD"];
NSURLConnection connection = [NSURLConnection connectionWithRequest:request delegate:self];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ([(NSHTTPURLResponse *)response statusCode] == 200) {
// url exists
}
}
Related
I am using Box's iOS SDK (https://github.com/box/box-ios-sdk-v2) and I am trying to get a URL to stream videos that are uploaded to Box.
I tried using the following method on the BoxFilesResourceManager class, but I do not see any special fields on https://developers.box.com/docs/#folders-folder-object that would get me a streaming URL
- (BoxAPIJSONOperation *)fileInfoWithID:(NSString *)fileID requestBuilder:(BoxFilesRequestBuilder *)builder success:(BoxFileBlock)successBlock failure:(BoxAPIJSONFailureBlock)failureBlock;
The only potential way to get a URL may be for me to get a shared link of the file and try to stream from that, but I hardly doubt that will give me the correct URL
Thanks
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://api.box.com/2.0/files/%#/content", fileId]]];
NSString *bearerToken = [NSString stringWithFormat:#"Bearer %#", accessToken]; // the access tokes must be valid(not expired)
[request addValue:bearerToken forHTTPHeaderField:#"Authorization"];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
// NSURLConnection Delegate method
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"streamable url: %#", response.URL);
}
I'm looking to set up a flag on a webserver, just so that I can change something after I release my app to the app store in case a bug doesn't go away. I'm not familiar with network connections, but I've put together the following:
- (void) loadThumbnailFlag
{
NSURL *url = [NSURL URLWithString:#"http://www.myappsite.com/ThumbnailFlag"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([httpResponse statusCode] / 100 == 2)
{
self.thumbnailFlag = YES;
}
else
{
self.thumbnailFlag = NO;
}
}
Is there anyway to improve this code so it's not wasting any steps as just to check if the flag exists or not (i.e. it's not trying to download a file or anything).
If you don't need the body, only the response, then it's best to either set the request to type HEAD ([request setHTTPMethod:#"HEAD"]; create an instance of NSMutableURLRequest), or to call cancel on the connection in connection:didReceiveResponse:.
If the server doesn't actually return any body data then it won't make a big difference, but it makes your intentions for the connection clear.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to objectiveC,
I have a problem in retrieving JSON type from a url, the url represent a web service which had built to return both JSON and XML, when I tried to consume the web service from the url the result was XML,
what I need is to determine the type of returning data to be JSON in the request.
by the way I am sure that the web service return both XML and JSON.
and here is my code where I get XML:
NSURL *url = [[NSURL alloc] initWithString:#"http://192.168.1.1:8080/test2/eattel/restaurants"];
NSString *result=[[NSString alloc] initWithContentsOfURL:url];
NSLog(#"%#",result);
the result is :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<restaurantImpls>
<Resstaurant Name="Abo Alshamat" PhoneNumber="0991992994" MobileNumber="0991992993" LastName="Shame" ID="1" FirstName="Samer"/>
<Resstaurant Name="AL-Kamal" PhoneNumber="0992993995" MobileNumber="0992993994" LastName="Ali" ID="2" FirstName="Ahmad"/>
<Resstaurant Name="Abo-MAhmoud" MobileNumber="0993377800" ID="12"/>
<Resstaurant Name="Four Season" PhoneNumber="0993994996" MobileNumber="0993994995" LastName="Ammar" ID="3" FirstName="William"/>
<Resstaurant Name="uuuuu" MobileNumber="0999555777" LastName="William" ID="20" FirstName="Ammar"/>
<Resstaurant Name="NewOneFromI2" MobileNumber="0999888777" ID="18"/>
<Resstaurant Name="JOURY" PhoneNumber="0999999998" MobileNumber="0999998997" ID="4"/>
<Resstaurant Name="TestTestRestaurant,Ammar,Hamed" MobileNumber="202020" ID="19"/>
</restaurantImpls>
thank you for your time.
We couldnt set the response data type from our request. Response is set from the server. From your description(web service return both XML and JSON), my guess is you need to post a status variable which showing the return status like isXML. It's only my guess. You need to contact server side programmers about the implementation of this request.
EDIT
Try below code
responseData = [[NSMutableData alloc]init];
NSURL *url = [[NSURL alloc] initWithString:#"http://192.168.1.1:8080/test2/eattel/restaurants"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/json" forHTTPHeaderField:#"accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
(void)[NSURLConnection connectionWithRequest:req delegate:self];
Then You need to implement NSURLConnection Delegates.
#pragma mark - NSURLConnection Delegates
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
}
I came across NSURLConnection, I used it before, simply on request, and getting data and parsing it. However this time web developer has developed GET and POST requests.
I want through many tutorials and stack question and tried to get desired result.
As I see there is sometime request, like this
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"URL"]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
[request setHTTPMethod: #"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
also few others I have seen.
I looks easy but I am unable to find what is required for any POST and GET request.
The data which I have received from my web developer is
SOAP 1.2
POST /DEMOService/DEMO.asmx HTTP/1.1
Host: projects.demosite.com
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
and in return there will be GET and POST
The following is a sample HTTP GET request and response. The placeholders shown need to be replaced with actual values.
GET /DEMOService/DEMO.asmx/VerifyLogin?username=string&password=string&AuthenticationKey=string HTTP/1.1
Host: projects.demosite.com
I am well-aware of delegates of NSURLConnections, which are following..
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
}
THE ONLY THING WHERE I AM STUCK IS
How to write request where I have pass arguments, in GET or POST request.
Thanks
If your arguments are being sent in the URL itself (e.g., as part of the URL path or query string), then you just need to include them in the NSURL argument. For instance, you might have the following:
NSString *urlString = [NSString stringWithFormat:#"https://hostname/DEMOService/DEMO.asmx/VerifyLogin?username=%#&password=%#&AuthenticationKey=%#",
username,
password,
authenticationKey];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
where username, password, and authenticationKey are local variables you set elsewhere.
Your response from the server is stored by the data contained in the NSData instance returned by -[NSURLConnection sendSynchronousRequest:returningResponse:error:].
So in your example, your response above would be stored in the response1 variable. And you can convert this to a string and/or parse it as needed.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I'm making an iPhone app in which you need to supply your username and password. It then needs to login to a website, and extract some text from the webpage that the user would be redirected to (if using a web browser) - this text would then need to be displayed. I have both URLs: the one to log in, and the "homepage" (first page seen when logged in).
If I type into my web browser:
https://[rest of URL]/[form name].asp?username=[my username]&password=[my password]
it redirects me to my "homepage". If I had logged in before, the website would remember that I was logged in and therefore I could go straight to the "homepage" without having to re-check my credentials.
How should I go about doing this? I'm quite new to NSURL and NSURLRequest so I have no idea where so start, given that there aren't really any tutorials that helped me.
Try using this block code:
NSString *urlAsString = #" http:// www.apple.com";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:queue
completionHandler: ^(NSURLResponse *response,
NSData *data,
NSError *error) {
if([data length] > 0 && error == nil) {
NSString *html = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
} else if([data length] == 0 && error == nil) {
NSLog(#"Nothing was downloaded.");
} else if (error != nil) {
NSLog(#" Error happened = %#", error);
}
}];
Thats a common scenerio, just post a request and asynchronously get the response, see code below
-(void)Login
{
NSURL* url = [[NSURL alloc] initWithString:#"https://[rest of URL]/[form name].asp"];
NSMutableURLRequest* request =
[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString* postString = #"username=[my userna
me]&password=[my password]";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncodi
ng]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data
{
//assign data to your property, this is the result of the post
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//your business code to deal with the content of the response from your http request
}