I am using the following code to make sure that if the URL is available:
NSString *const URL = #"http://some_url/";
-(BOOL) isURLReachable
{
NSHTTPURLResponse *response;
NSError *error = nil;
NSURL *url = [NSURL URLWithString:URL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendSynchronousRequest:request returningResponse:&response
error:&error];
// just for testing
NSLog(#"checking response!");
return [response statusCode] == 200;
}
I can only reach the url when I am connected to the company's network which is okay. But when I go outside or on my 4G network I still get status code 200. Further investigation revealed that if the URL is not available then Tmobile searches for the URL and displays in a search view and returns status code 200. I do not want that? If the URL is not reachable then I would like to know that it is not reachable. How can I proceed?
Related
I'm trying to connect to a web service that if I hit it through Safari I get back some json, but when I hit it through code I get a NSURLErrorDomain error with the following description.
"The certificate for this server is invalid. You might be connecting to a server that is pretending to be "url" which could..."
Here is the code:
NSURL *url = [NSURL URLWithString:#"webservice_url"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
Can anyone explain how to get around this? Also, it is a https web service.
The website doesn't have a HTTPS certificate. Try looking into this:
https://stackoverflow.com/a/15011030/4716039
In your code, the URLWithString value needs to be an actual URL. It is the same thing as going to Safari and typing in "webservice_url" as the entire URL instead of giving it the entire address. Instead you'll want to do something like the following:
NSURL *url = [NSURL URLWithString:#"https://www.urlgoeshere.com/getJSON"];
You can use like this -
NSURL *baseURL = [NSURL URLWithString:#"http://example.com/v1/"];
[NSURL URLWithString:#"foo" relativeToURL:baseURL];
// http://example.com/v1/foo
I want to like and comment in my iOS application.But the problem is whenever I call my API the response comes in the form of this `error:message:(#200)'. App does not have permission to make this call and sometimes it will give input parameter is required.The permissions i give are 'basic_info','email','user_likes' and 'read_stream'. I am passing object id and access token in my like and comment API.
Like API code:
NSString *theWholeUrl = [NSString stringWithFormat:#"https://graph.facebook.com/%#/likes?access_token=%#",self.friendId,[FBSession activeSession].accessTokenData.accessToken];
NSLog(#"Value of theWholeUrl%#",theWholeUrl);
NSURL *facebookUrl = [NSURL URLWithString:theWholeUrl];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:facebookUrl];
[req setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
You need the publish_actions permission to be able to like and comment on content programmatically via the API.
I want to get a MP3 link from a website, I don't know exactly what type of this website is, but it only has content like this (link: http://www.nhaccuatui.com/download/song/4Upyxq0QlytX)
{"error_message":"Success","data":{"stream_url":"http:\/\/download.s81.stream.nixcdn.com\/dd634cb8afcc15d7c17a8ce4c548709f\/533cc58e\/NhacCuaTui791\/KhongQuanTam-ChiDan_4cyw4_hq.mp3","is_charge":"false"},"error_code":0,"STATUS_READ_MODE":true}
What can I do if I want to get content (link mp3) from key (?) "stream_url" from this link to put it in to my iOS Applications?
If you rearrange your JSON it will look like this:
{
"error_message":"Success",
"data":{
"stream_url":"http:\/\/download.s81.stream.nixcdn.com\/dd634cb8afcc15d7c17a8ce4c548709f\/533cc58e\/NhacCuaTui791\/KhongQuanTam-ChiDan_4cyw4_hq.mp3",
"is_charge":"false"
},
"error_code":0,
"STATUS_READ_MODE":true
}
From that you can see its a dictionary.
If you want to get it via url request do something like this:
NSDictionary *dictionaryData;
NSURLRequest *requestURL = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.00];
NSHTTPURLResponse *response;
NSError *error = [[NSError alloc]init];
NSData *apiData = [NSURLConnection sendSynchronousRequest:requestURL returningResponse:&response error:&error];
dictionaryData = [NSJSONSerialization JSONObjectWithData:apiData options:kNilOptions error:&error];
Then you can get the url by doing this:
NSString *str = [[dictionaryData objectForKey:#"data"] objectForKey:#"stream_url"];
Then make another request for getting the file.
The data you presented is in JSON format. To access it, use NSJSONSerialization.
I have a simple method that takes a url and loads it from the server:
- (void)loadURL:(NSString*)url
{
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
request.HTTPMethod = #"GET";
request.URL = [NSURL URLWithString:url];
NSHTTPURLResponse* response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
}
The server returns a response with max-age of 1 day.
Problem is that when I run these 3 lines repeatedly, 2 of them randomly miss the cache and reload the response:
[self loadURL:#"http://192.168.0.105:8080/users/51bdbc73808897302f000001/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09RoyipmXgcENwfE6EV9yzvgp5VTSZww"];
[self loadURL:#"http://192.168.0.105:8080/users/51ee9d4e263d08fe04000003/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09RoyipmXgcENwfE6EV9yzvgp5VTSZww"];
[self loadURL:#"http://192.168.0.105:8080/users/51d17b81de38c60b20000006/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09RoyipmXgcENwfE6EV9yzvgp5VTSZww"];
If I add some random unique data (&x, &y, &z) to each request's query string it fixes the problem:
[self loadURL:#"http://192.168.0.105:8080/users/51bdbc73808897302f000001/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09RoyipmXgcENwfE6EV9yzvgp5VTSZww&x"];
[self loadURL:#"http://192.168.0.105:8080/users/51ee9d4e263d08fe04000003/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09RoyipmXgcENwfE6EV9yzvgp5VTSZww&y"];
[self loadURL:#"http://192.168.0.105:8080/users/51d17b81de38c60b20000006/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09RoyipmXgcENwfE6EV9yzvgp5VTSZww&z"];
Also, if I reduce the length of query strings to 80 chars it fixes the problem as well:
[self loadURL:#"http://192.168.0.105:8080/users/51bdbc73808897302f000001/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09Royipm"];
[self loadURL:#"http://192.168.0.105:8080/users/51ee9d4e263d08fe04000003/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09Royipm"];
[self loadURL:#"http://192.168.0.105:8080/users/51d17b81de38c60b20000006/avatar?size=200x200&access_token=abcdefghijklmnopqrstuvwxyzzp77eDLqub3EWfXGe4c09Royipm"];
What's going on?
Is this a bug in iOS? How can I fix it?
P.S: I've tested this in an empty application with no extra stuff both on iOS 5 and 6.
Set the caching behaviour in the NSURLRequest with requestWithURL:cachePolicy:timeoutInterval:. Try:
- (void)loadURL:(NSString*)url
{
NSURL *url = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];
NSHTTPURLResponse* response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
}
Possibly also use NSURLRequestReloadIgnoringLocalAndRemoteCacheData for cachePolicy.
you might want to use ASIHTTPRequest instead
http://allseeing-i.com/ASIHTTPRequest/
This is the logical flow for my application:
At first, when the view controller has finished loading, then a NSURLConnection request can start its execution
The response consists in xml data
After parsing that xml I need to send another NSURLConnection request.
After sending the second request, if the response is ok, I receive other xml data
After parsing the second xml, I have to check some issues between first and second xml data.
So, is it possible to send multiple request? How? I do not need code, you could just explain it.
Thank you in advance.
I do this with the NSURLConnection Making them properties, then checking which one it is:
#property (nonatomic,retain) NSURLConnection *myConnection;
#property (nonatomic,retain) NSURLConnection *mySecondConnection;
then in the delegate:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if (connection == myConnection){
//do something
}
if (connection == mySecondConnection){
// do something else
}
}
You can pass your NSURLRequest to the connection:
self.myConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
There is a third party library available which is a wrapper on CFNetwork is ASIHTTPREQUEST
This Library should do work for you. so that you don't have to write the code from scratch. other alternative is create one class which will be responsible for creating NSURLConnection then sending the request and finally notify to view controller using delegate or notification one data is received .
- (void)viedDidLoad{
[super viewDidLoad];
[self firstRequestMethod];
}
- (void)firstRequestMethod{
NSString *myFirstRequestURL = #"<URL>";
NSURL *webURL = [NSURL URLWithString:myFirstRequestURL];
NSURLRequest *request = [NSURLRequest requestWithURL:webURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSError *error;
NSURLResponse *response;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(returnData)
{
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];
//Parse your response here.
//Is desired response obtain call the second Request, as described above
if (TRUE) { //on success
[self secondRequestMethod];
}
}
}
- (void)secondRequestMethod{
NSString *mySecondRequestURL = #"<URL>";
NSURL *webURL = [NSURL URLWithString:mySecondRequestURL];
NSURLRequest *request = [NSURLRequest requestWithURL:webURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSError *error;
NSURLResponse *response;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(returnData)
{
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];
//Parse your response here.
//Is desired response obtain call the second Request, as described above
if (TRUE) { //on success
//subsequent calls to other url, same as above
}
}
}
Hope this will help you understand better....