When I am connected to internet then It works perfect but when Internet is not connected then I go error on following lines:

$socket_context = stream_context_create($options);

$this->smtp_conn = @stream_socket_client($host.":".$port, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $socket_context);

I am intentionally not connected to internet and i want to show alertView in iOS app to user when user is not conneted to internet that :

You are not connected to internet

Instead of

Warning : stream_socket_client( ) , php_network_getaddresses getaddrinfo failed nodename nor serv name provided or notknown

So how can i handle that error ?

// -------------- Code where I am setting NSStream in .m file :----------

#import "LoginViewController.h"

// --------------- here I set the delegate -------------
@interface LoginViewController () <NSStreamDelegate>

-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{

}

Any help will be appreciated.

2

There are 2 best solutions below

8
On

Assuming you are using NSStream to connect your sockets. In your delegate method

-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode

You will be notified if the socket has an error with:

case NSStreamEventErrorOccurred:

or

case NSStreamEventEndEncountered:

In which case you can show the network error to your user. If however they lose internet connection you won't know until you try to send some data over the socket. So to get around this problem you should implement Reachability.

Github project

or the Apple helper class.

Apple Reachability

You will be notified when there is no connection as well as when there is a connection allowing you to notify the user as needed.

Hope I understood correctly.

2
On

Wait... so in your scenario, the iPhone app is the "socket server", relative to which PHP is a "socket client". Am I getting this right?

Assuming so... You've already silenced the error message with "@". The only thing remaining is that you simply check if the return value is false, e.g.

$socket_context = stream_context_create($options);

$this->smtp_conn = @stream_socket_client($host.":".$port, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $socket_context);
if (false === $this->smtp_conn) {
    //Handle the error here
    echo 'You are not connected to internet';
}

If using the "@" operator makes you feel dirty (as it should), you could also use set_error_handler() right before the call, and handle the error there if it occurs, and finally restore the error handler to its previous state.