How do I detect real network availability? - iphone

when iPhone connects to a wireless router, and that router is not connected to the internet? i need to display an error message saying "check you internet connection" i tried the Reachability sample code. but no luck,
http://developer.apple.com/library/ios/#samplecode/Reachability/Listings/ReadMe_txt.html
when i disable the WIFI in phone it's working fine, i tried the Checking For Internet Connectivity in Objective C sample code "isDataSourceAvailable" even itz not working,can any one help me to fix this issue, really appriciate.

You could do something like this:
+ (BOOL) pingServer
{
NSURL *url = [NSURL URLWithString:#"http://some-url-that-has-to-work/"];
NSURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSHTTPURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:NULL];
return (response != nil);
}
This is a synchronous request, so that it will block the current thread. You can do the whole network check in a background thread, so that blocking it won’t matter, or you can send the request asynchronously. Also you might want to set the HTTP method to HEAD, so that you won’t download the whole resource.

I recommend you do the same as Microsoft does, and to be really wicked, you can even use their servers, since they probably will make sure those are on line for the foreseeable future.
They look up a hostname and then access a very small file on a web server.
See the same question on serverfault (from a non programming perspective of course.)
Basically look up the IP address for a hostname (in that example "dns.msftncsi.com"), then access the URL, for example http://msftncsi.com/ncsi.txt. This can be done with simple socket programming if you like, real HTTP not necessary.
Open a socket to port 80, on the IP you found by looking up the hostname.
Send a string to the socket like so:
"GET /msftncsi.com/ncsi.txt HTTP/1.1\nHost: msftncsi.com:80\n\n"
Then wait for something to return. If anything returns, even a single byte, it means you have Internet access.
Or at least access to this server, which in this example is Microsoft.

https://github.com/adib/asi-http-request/blob/master/External/Reachability/Reachability.h
This is a part of the ASI HTTPRequest project on git. It extends Apple's example and apparently is good enough for quite a few apps in the store (see ASI's wall of who's using: http://allseeing-i.com/ASIHTTPRequest/Who-is-using-it)
Anywho, I know an answer was already accepted, but just for further reference.

Related

iOS - 3G slow connection issue when connecting to back-end API server

Currently I am working on an App which requires several calls to a back-end server.
When on WiFi the App connects fine and downloads very fast the data, but when on 3G the connection seems a bit unstable and very slow.
So I have done some very simple test case (which you find below). And it seems that NSURLConnection is not getting data at the same response speed.
(Do note that I have removed the URL of the real server I connected to)
Test cases:
Placed on a server the following php script:
<?php echo 'hello world' ?>
Grabbed an iPhone, put WiFi off and made sure it had a proper 3G connection.
Used the following Objective-C code to connect to the server:
NSURL * url = [NSURL URLWithString:#"http://someserver.com/test.php"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSDate * startDate = [NSDate date];
NSLog(#"START");
NSURLConnection * connection = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"%3.2f", -[startDate timeIntervalSinceNow]);
This returns on 3G - 1.47 seconds. So this might be normal if you connect for the first time using 3G, since it needs to initialise. But now comes the interesting part. If you repeat this call several times it returns the following:
1.47 seconds
2.33 seconds
1.1 seconds
I have tested this using two different iPhones and two different providers:T-Mobile and KPN. I also tried this using the async version of NSURLConnection, which I normally use, but this also returns the same results.
(Other things I also did: checked Apple's Reachabilty.h, removed the DNS look-up by replacing the server url by the ip-number, used an other server and used https://www.google.nl/search?q=%i, arc4random(), also tried [NSString alloc]initWithContentOfURL]. All returned a similar result, except when using the iPhone browser: Safari, which responded immediately.)
I have also tested something similar using an Android phone, but then I get a fast response 500ms (using the same providers).
Did someone encountered this before? If so, how did you solve this issue and what causes this problem with the connection?
I have a similar issue in that naturally over a 3g connection the post request would be slightly slower depending on the amount of data sent. However if I send over a synchronous request its quicker for me than the async method. What I have noticed is that over a 3g connection using async the OS has to close the connections and you may notice in the log "purgeIdleCellConnections: found one to purge conn" seems to add some time to method execution.

HTTP post with UIWebview?

I am quite new to Objective-C coding, learning at College at the moment so. Anyways, how do I perform a HTTP post with a UIWebview so that I can update the view when needed for a different flyer to put put there etc.
I may not even need to use HTTP post doing this, but my co-partner who is coding for Android insists I may need to!
Any help?
I'm not sure what you mean by flyer. But if you want a web page to appear in a UIWebView you don't need to use HTTP post, you just pass the url of a page to load to the UIWebView, or if you already have html content etc. you can load that content directly.
You can make HTTP requests directly but you probably don't need to. What exactly is it you want to display in the UIWebView?
To make an HTTP Connection start by learning about NSURLConnection at iOS Developer Library
The first thing you're going to want to start with is making your NSURL objects then make your NSURLRequest with the parameters as well as the URL of your request. Then make a NSURLConnection and initiate the connection either asynchronously (preferred) or synchronously. If you want a synchronous (blocking) connection initialize it like so
NSError *error;
NSURLResponse *responseHandler;
NSData *response = [myNSURLConnection sendSynchronousRequest:myNSURLRequest, returningResponse:&responseHandler,error:&error];

ASIHTTPRequest and NSURLConnection

I need to work with ASIHTTPRequest in my app but i'm an absolute beginner in everything that concerns http, json, connections to server and stuff like that, so i decided to learn the basics first and i've got few really dumb questions for you. I have already googled looking for the answers, but all in vain
1)Does NSURLconnection have something to do with http protocol and http prequests? Is it useful for me to get acquainted with this class since i'm gonna work with http requests?
2)A huge problem of mine is that i do not have a web server yet to test my requests and i've been wondering if there is a free web server available for those who just want to upload/download data (images and may be something else) to/from it in order to learn basics of working with servers.
3)As far as i know development of ASIHTTPRequest library has been ceased. Does it mean that this library will become unavailable soon? Should i look for a different library? And btw is there a better one?
Thanks in advance
1.you use NSURLConnection to create a request object from a NSUrl. Here is an example, I used it to load a url to a UIWebView :
//Set the URL to go to for your UIWebView
NSString *urlAddress = #"http://google.com/";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//load the URL into the web view.
[aWebView loadRequest:requestObj];
You can read more about it here:http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html
NOTE : also look at NSMutableURLRequest, which is a subclass of NSURLRequest
2.To test, you can install apache on your computer and access it using http://localhost/.
If you are using windows, download WAMP : http://www.wampserver.com/en/
and if on mac, just search google how to install apache through terminal.
3.I havent used ASIHTTPRequest in a long time but as far as I remember it was a good library . if it is being ceased, then that probably means they wont be publishing anymore updates and/or fix bugs, so yes I think its better to use an active project that is being updated constantly. I also havent found any warning on their site about it, so I doubt they are stopping the project.
1) Yes NSURLConnection deals with HTTP and others protocol. But it isn't so simple to use than ASIHTTPRequest
2) Create a dropbox account and use the Public folder. Then right click on the file and select Dropbox > copy public link. You have a Webserver!
3) AFNetworking is really great

sending information from my iphone app to my computer

So I have a pretty simple problem, which I have no idea how to go about (kinda of new for everything here). I am developing an iPhone app that I intend to use only myself - so think small for now :)Let's say all my app is doing is tracking my location every hour. All I want to do, is to be able to read this information not on the iphone, say on a file on my computer. How can I send this information from my app to a personal computer? I am guessing that I will need to set up some server / database or something on my personal machine?
Can someone please help with a quick step by step on how to go about that? I literally have no clue where to start...
Thanks!
You just need a http server and then you cam create HTTP GET/POST requests to url's set up on your machine. You can use the responses to send data back to the device.
You'll need to have a listener somewhere to send your data to. For instance, you could set up a communication class in your project which would be responsible for serving as the medium between your applications. You would then set up a listener on a server, or your machine that would listen for requests.
iPhone > Communication Class > Web service
(.NET in this case)
You can use the NSURLConnection object to serve this purpose. E.g.
- (void) sendSomethingToServer:(NSString*)myData{
NSString*url = [[NSString alloc]initWithFormat: #"http://example.com/service.asmx/RecordData?myData='%#'", myData];
[self createRequest:url];
[url release];
}
http://example.com/service.asmx/RecordData being the location and method on your web service.
Here's a generic request method I created which sets the headers as a JSON packet.
- (void) createRequest: (NSString*)urlFormatted {
NSLog(#"Request Sent");
NSURL *url = [NSURL URLWithString: urlFormatted];
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL: url];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
}
And on the back-end, on your web server, you would have a method that recieves the data. Obviously you could use any technology you wanted on the server. In this example, I'm using .NET on Mono e.g.
[WebMethod(Description = "Generic Client Data)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string RecordData(string myData)
{
// Do something with data
}
Set up a Ruby on Rails server on your Mac. It's free and quite easy.
Use ASIHTTPRequest to send data to the Ruby server.
http://allseeing-i.com/ASIHTTPRequest/
If you just need to get the data back and forth, I believe you could use file sharing. Here's a tutorial on how to set that up:
http://www.raywenderlich.com/1948/how-integrate-itunes-file-sharing-with-your-ios-app
It would allow you to view the files in itunes and copy them back and forth when the iPhone is connected via USB. If all you need to do is to get a raw data file onto your computer, that would likely be a lot less overhead than having to build/run a full server just to transfer the file over.
Apple's can you help get started. Search for "networking" in the docs and develop a client on both sides which uses your own protocol.

Is it possible to read the contents of a web page into a string so i can parse out the data?

I'd like to be able to get my iphone to load a URL( or really the file that the url points to) into a string. The reason I want to be able to do this is so that I can then parse the string looking for tags and extract some values from it.
The files are mostly webpages so html or .asp etc.
Anybody able to give me some hints on what I need to do to achieve this kinda of thing?
Many Thanks,
-Code
First get the URL
NSURL *anUrl = [NSURL URLWithString:#"http://google.com"];
Then turn it into a string
NSError *error;
NSString *htmlString = [NSString stringWithContentsOfURL:anUrl encoding:NSUTF8Encoding error:&error];
UPDATE:
There is documentation on getting the contents of an URL by using NSURLConnection from the ADC site
From there you can get the string representation of the downloaded data using
NSString *htmlString = [[NSString alloc] initWithData:urlData encoding:NSUTF8Encoding];
I appreciate that this has been asked and answered, but I would strongly suggest that you consider not using NSString's stringWithContentsOfURL:encoding:error: method for this. If there's one message Apple has tried to send to iOS developers over the past year it is this: Do not make synchronous network calls on the main thread.
If that request takes more than twenty seconds to respond, which is not at all unlikely with a 3G or EDGE connection, and certainly possible on a WiFi connection, iOS will kill your app. More importantly, if it takes more than about half a second to return you're going to anger your users as they fiddle with their unresponsive phones.
NSURLConnection is not terribly difficult to use, and will allow your device to continue responding to events while it's downloading content.