This question already has an answer here:
Determine whether iPhone is really connected to the internet or just behind a restricted hotspot
(1 answer)
Closed 7 years ago.
There are loads of questions on here about finding an active internet connection in an app, but none work if you are on a 3g connection and you have no data credit, or if you are on a WiFi network at a hotel that automatically redirects to a log in page and you have yet to enter the password. That kind of situation.
What is the fastest way to check if the internet connection is actually operational?
You can use AFNetworkReachabilityManager class in AFNetworking.
https://github.com/AFNetworking/AFNetworking
above link will help you out in setting things. This will provide you with continuous network check as per your requirement. Here is few line of code:
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(#"Reachability: %#", AFStringFromNetworkReachabilityStatus(status));
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
The best way to accomplish this, not using Reachability or any other API, is by creating a NSURL and to try to receive data from it. For the bad connection I added a timeout of 20sec.
Like:
- (void)checkConnection //Run this on a side queue, never on a main queue
{ NSURL *checkURL = [NSURL URLWithString:#"http://www.apple.com"];
NSURLRequest *lRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:checkURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:20.0];
NSData *data = [NSData dataWithContentsOfURL:lRequest];
if (data)
{
connected = YES;
}
else
{
connected = NO;
}
}
That would check if a specific website is reachable and set a timeout which indicates a slow network connection.
This code could have errors, as I haven't used/tried it yet! Comment this answer if there are any.
Related
This is for www.pusher.com.
iOS lib they provided is libPusher. After I installed and follow the first step, it just not working. I've heard a few people make it work. Is this library still alive or it doesn't support newer version of iOS?
PTPusher *client = [PTPusher pusherWithKey:#"app-key" delegate:self encrypted:NO]; // I assume this is "key" not "secret" there.
[client connect];
PTPusherChannel *channel = [client subscribeToChannelNamed:#"test"];
NSLog(#"Channel: %#, %d", channel, channel.isSubscribed);
I've implemented delegate methods to track status. After [client connect] called, the delegate method: - (BOOL)pusher:(PTPusher *)pusher connectionWillConnect:(PTPusherConnection *)connection trigged, but then nothing happened after this. No error messages, no success messages. Since the clint is not connecting, the channel is not subscribed either.
I've implemented pusher on JS and it worked. Since what I did is very basic client connection and there is nothing I can do about (At least from documents), so I assume maybe this library just not working anymore.
I was being dumb and ignored that the document said pusher client should be strong. Therefore, the solution should be:
#property(nonatomic) PTPusher *client;
self.client = [PTPusher ...];
...
AFNetworkReachabilityManager *mgr=[AFNetworkReachabilityManager sharedManager];
[mgr startMonitoring];
[mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//NSLog(#"Reachability: %#", AFStringFromNetworkReachabilityStatus(status));
if ([AFNetworkReachabilityManager sharedManager].reachable) {
NSLog(#" ONLINE");
}
else
{
NSLog(#"OFFLINE");
}
}];
This is how I tested reachability through AFNetworking now! How to check reachability in specific domain? And how does AFNetworking uses to test the reachability ?
[AFNetworkReachabilityManager managerForDomain:#"www.google.com"]; didn't work
Couple of things.
First, you really should configure the manager before starting monitoring. In this case this means you should call setReachabilityStatusChangeBlock before calling startMonitoring.
Second, when you're creating new AFNetworkReachabilityManager by using managerForDomain:, you are responsible for managing lifetime of the object. If you use code above with ARC enabled, mgr will be deallocated as soon as it goes out of scope meaning that there will be no manager to monitor reachability. One solution is to make mgr an instance variable of a class, e.g. an application delegate.
/**
Creates and returns a network reachability manager for the specified domain.
#param domain The domain used to evaluate network reachability.
#return An initialized network reachability manager, actively monitoring the specified domain.
*/
+ (instancetype)managerForDomain:(NSString *)domain;
this is from the afnetworking source code,
to monitor a specified domain, just create a reachability manager for that domain using this class method. like this
AFNetworkReachabilityManager *mgr= [AFNetworkReachabilityManager managerForDomain:#"www.google.com"];
My question might have a very easy answer but I am not going anywhere on Google with the keywords I am using. Let me explain, it surely will be clear to one of you.
In my app, I am uploading a string to a server. If the connection is successful, the user gets a "done" message and if not, I tell him what to do next.
I was testing this afternoon with the "no network simulator" and it works well, but I had to wait may be 90 seconds before I get the message "no connection available". I don't know for how long it tries to connect in real life, but I found the wait really annoying and wouldn't like my user to be in such a situation.
My question is : I want the app to try and connect to the server for say 20 seconds and if after that time it hasn't succeeded, it stops trying and the user decides if he wants to try a second time or not ?
My apologies in advance, English isn't my mother tongue.
Thank you for pointing me to the right direction.
You should set timeout interval in session configuration
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.timeoutIntervalForRequest = 20;
configuration.timeoutIntervalForResource = 20;
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
// in case if you are using AFNetworking
// AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
I'm using AFNetworking in my app to connect / download data from a web service. This app is deployed via Enterprise deployment to users at various locations. At one of the locations where people use our app, the wifi network seems to randomly go down / come back up in a few seconds. In these cases, the requirement was to retry a request thrice before giving up and failing. I've got the retry part of it working fine, but have some problems detecting a network failure. Some code:
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation, id responseObject) {
[self parseResponse:operation.responseString];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[self messageFailureWithCode:error.code
reason:[NSString stringWithFormat:#"%#", error]];
}
];
The error code I'm retrying on is NSURLErrorTimedOut. But I just got another log file which indicated a failure with the following error: -1003 "A server with the specified hostname could not be found."
I could add this code to my list too, but I wanted to be sure that I'm capturing all the errors and not just handling them as they appear. I was looking through the NSURLError.h file and found the following error codes that vaguely look like they could be caused by a network failure.
Can someone help me figuring out under what conditions each error is triggered and if I'm missing any error codes? The list is below:
NSURLErrorCannotFindHost
NSURLErrorTimedOut
NSURLErrorCannotConnectToHost
NSURLErrorNetworkConnectionLost
NSURLErrorDNSLookupFailed
NSURLErrorResourceUnavailable
NSURLErrorNotConnectedToInternet
Thanks,
Teja.
It sounds like you could safely just retry every failure with an error domain of NSURLErrorDomain (exempting the case where an operation was cancelled). That should cover all of those cases.
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 10 years ago.
Well , I have just started coding in general. I am trying to make an ios social app with basic picture information taking data from a website ( some what of a flickr-clone)
So , the main website will be built on Ruby on rails.
EDIT :
ok so , i want to know when a person uploads a picture , it will have the following entries:
* name
* who took
* location
I was researching about the gem logtrend (https://github.com/gorsuch/logtrend) , i was wondering if I can make a trending feed of sorts using location?
eg: the user selects a tab which shows them the trending pic ( near them (based on his core location) ?? Can we do something like that ?
I don't know anything about Ruby on Rails but I do know to do what you're trying to do (let user upload photos with their name and GPS location to a server, then allow other users to view that photo by downloading it down to their app).
One way you can build the server is to build a web service with Ruby on Rails.
Web Servcie
The web service (your server) does 2 things:
1) Accept a Request
2) Return a Response
With the web service, you accept HTTP POST or GET request, then your server's logic code will parse the "parameters" or "variables" inside the POST or GET.
Once your server has these variables, it can save them to the database (an ORM would really make it easier).
Your web service can then return a response using HTTP Status Code or a JSON formatted response.
Example Scenario
1) iPhone app takes photo and then makes a HTTP POST request to your Ruby server using ASIHttpRequest or AFNetworking.
// ASIExample
-(void)uploadPhotoToServer
{
NSURL *url = [NSURL urlWithString:myUploadWebServiceURL];
__block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
// ---------------------------------------------------------------
// setting the POST parameters below
// note: you will need to get the NSData from a UIImage object
// ---------------------------------------------------------------
[request setData:imageData withFileName:#"myphoto.jpg" andContentType:#"image/jpeg" forKey:#"photo"];
[request setPostValue:fldName.text forKey:#"name"];
[request setPostValue:[NSNumber numberWithDouble:myLatitude] forKey:#"latitude"];
[request setPostValue:[NSNumber numberWithDouble:myLongitude] forKey:#"longitude"];
[request setCompletionBlock:^{
int statusCode = [request responseStatusCode];
if(statusCode == 200)
{
[self alertUploadComplete];
}
}];
[request setFailBlock:^{
NSLog(#"Server error: %#", [[request error] localizedDescription]);
[self alertConnectionProblem];
}];
[request startAsynchronous];
}
2) Server receives the request, parses the data and returns a response
// Symfony Web Framework example (PHP based web framework)
public function uploadPhotoAction()
{
// --------------------------------------------------
// check to make sure all POST parameters are sent
// in the POST request by iPhone app.
// --------------------------------------------------
if(
!isset($_REQUEST['name']
|| !isset($_REQUEST['latitude']
|| !isset($_REQUEST['longitude']
|| !isset($_REQUEST['photo']
)
{
return new Response($this->sendResponse(406, 'Missing POST parameters');
}
else // assumes safe to continue
{
/*
write code to save the your name, latitude, longitude to your database here
*/
/*
save your photo to your server's dedicated photo folder, then store
the file path to the file in your database entry in the above step
*/
return new Response($this->sendResponse(200, 'Photo uploaded'));
}
}
A couple of gems that you could make use of are Devise coupled with OmniAuth for social logins/authentication.
For more gems by categories, check out Ruby Toolbox.
Hope you the best of luck!
Is this achievable through ruby on rails ?
Yes, yes it is.
what gems should I be using ?
Depends upon your approach and featureset.
Also , which gems can be used to make API's to feed the IOS app ?
I think you're misunderstanding what an API is. The API is HOW the client will interact with the host.
I would suggest you investigate using JSON to communicate between your IOS app and your Web app. Both IOS and Ruby/Rails are very capable of supporting JSON and it is relatively lightweight.
Also, you need to define, in detail, what the IOS application is going to do where it needs interaction with the Web app.
Example
IOS App (IA) will save a picture to the Web App (WA).
IA may save the same picture to WA (overwriting)
IA will be told if WA is full
IA will log into WA
IA can log out from WA
IA can change password on WA
WA will reject commands from a non-logged in IA
IA can retrieve user's pictures from WA
IA can retrieve any other user's pictures from WA
etc.
Now, for each one, you design the API to support that function.