Wednesday 26 June 2013

How to detect Network Signal Strenghth in iOS Reachability

@interface ViewController () <NSURLConnectionDataDelegate>

@property (nonatomic, strong) NSURLConnection *connection; // we'll use presence or existence of this connection to determine if download is done
@property (nonatomic) NSUInteger length;                   // the numbers of bytes downloaded from the server thus far
@property (nonatomic, strong) NSDate *startTime;           // when did the download start

@end

static CGFloat const kMinimumMegabytesPerSecond = 20;
static CGFloat const kMaximumElapsedTime = 2.0;

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self testDownloadSpeed];
}

- (void)testDownloadSpeed
{
    NSURL *url = [NSURL URLWithString:@"http://insert.your.site.here/yourfile"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    self.startTime = [NSDate date];
    self.length = 0;
    self.connection = [NSURLConnection connectionWithRequest:request delegate:self];

    double delayInSeconds = kMaximumElapsedTime;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        if (self.connection)
        {
            [self.connection cancel];
            self.connection = nil;
            [self useOffline];
        }
    });
}

- (CGFloat)determineMegabytesPerSecond
{
    NSTimeInterval elapsed;

    if (self.startTime)
    {
        elapsed = [[NSDate date] timeIntervalSinceDate:self.startTime];
        return self.length / elapsed / 1024;
    }

    return -1;
}

- (void)useOnline
{
    // use your MKMapView; I'm just updating a text field with the status

    self.statusLabel.text = [NSString stringWithFormat:@"successful @ %.1f mb/sec", [self determineMegabytesPerSecond]];
}

- (void)useOffline
{
    // use your offline maps; I'm just updating a text field with the status

    self.statusLabel.text = [NSString stringWithFormat:@"unsuccessful @ %.1f mb/sec", [self determineMegabytesPerSecond]];
}

#pragma mark - NSURLConnectionDataDelegate methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // I actually want my download speed to factor out latency, so I'll reset the 
    // starting timer when the download commences

    self.startTime = [NSDate date];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if (self.connection)
    {
        self.connection = nil;
        [self useOffline];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.connection = nil;

    if ([self determineMegabytesPerSecond] >= kMinimumMegabytesPerSecond)
        [self useOnline];
    else
        [self useOffline];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // you don't need to do anything with the downloaded data; 
    // just keep track of # of bytes

    self.length += [data length];
}

@end
The choice of kMinimumMegabytesPerSecond and kMaximumElapsedTime is obviously up to you. The first measures bandwidth, and the second also factors in latency. The thing is, to do accurate bandwidth test, you need to do prolonged and repeated downloads. But you also want to (a) to not use of too much of the user's data plan; nor (b) take too long. So, in my test, I was just downloading a file of 100kb and set my criteria to be loose enough to permit for a certain amount of variation in both latency and download speed, but you should play around with the values and use whatever suits you.

Monday 24 June 2013

Send sms through way2sms API

<?php
/*way2sms
 *used to send sms using web service
 *@ $uid       String:  username to authenticate the way2sms website
 *@ $pwd       String:  password for way2sms website
 *@ $phone     String:  phone numbers of recipients
 *@ $msg       String:  the message to be send
 */
class way2sms
{
    var $uid,$pwd,$phone,$msg;
    /*
    *@ constructor of way2sms class
    *
    *@ $id     String :  username to authenticate the way2sms website
    *@ $pass   String :  password for way2sms website
    *
    */
    function way2sms($id,$pass)
    {
        $this->uid=urlencode($id);
        $this->pwd=urlencode($pass);
    }
    /*
    *sendSMSToMany
    *@description : to send the sms
    *
    *@ $phone    String :  phone numbers of recipients
    *@ $msg      String :  the message to be send
    *
    *@return     array :  error message or success message
    */
    
    function sendSMS($phone$msg)
    {
        $curl curl_init();
        $timeout 30;
        $result = array();
        $autobalancer=rand(1,8);

        curl_setopt ($curlCURLOPT_URL"http://site".$autobalancer.".way2sms.com/Login1.action");
        curl_setopt ($curlCURLOPT_POST1);
        curl_setopt ($curlCURLOPT_POSTFIELDS"username=" $this->uid "&password=" $this->pwd);
        curl_setopt ($curlCURLOPT_COOKIESESSION1);
        curl_setopt ($curlCURLOPT_COOKIEFILE"cookie_way2sms");
        curl_setopt ($curlCURLOPT_FOLLOWLOCATION1);
        curl_setopt ($curlCURLOPT_MAXREDIRS20);
        curl_setopt ($curlCURLOPT_RETURNTRANSFER1);
        curl_setopt ($curlCURLOPT_USERAGENT"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
        curl_setopt ($curlCURLOPT_CONNECTTIMEOUT$timeout);
        curl_setopt ($curlCURLOPT_REFERER"http://site".$autobalancer.".way2sms.com/");
        $text curl_exec($curl);
        
        preg_match_all('/<input[\s]*type="hidden"[\s]*name="Token"[\s]*id="Token"[\s]*value="?([^>]*)?"/si'$text$match);
        $token $match[1][0]; 

        // Check for proper login
        $pos stripos(curl_getinfo($curlCURLINFO_EFFECTIVE_URL), "main.action");

        if ($pos === "FALSE" || $pos == || $pos == "") return array("Login Faild");

        if (trim($msg) == "" || strlen($msg) == 0) return array("Invalid message");
        
        $msgs $this->split_for_sms($msg);
        
        //$pharr = explode(",",$phone);
        $p=$phone;
        $refurl curl_getinfo($curlCURLINFO_EFFECTIVE_URL);
        $refurl_instantsms=0;
        // foreach ($pharr as $p)
        // {
            if (strlen($p) != 10 || !is_numeric($p) || strpos($p".") != false)
            {
                array_push($result,"Invalid number : " $p ". ");
                //continue;
            }
            foreach($msgs as $msg)
            {
                curl_setopt ($curlCURLOPT_REFERER$refurl);
                curl_setopt ($curlCURLOPT_URL"http://site".$autobalancer.".way2sms.com/jsp/SingleSMS.jsp?Token=".$token);
                $text curl_exec($curl);
                
                preg_match_all('/rqMob=["\']([\d\w]+)["\'];/si'$text$match);
                $rqMob=$match[1][0];
                preg_match_all('/rqTok=["\']([\d\w]+)["\'];/si'$text$match);
                $rqTok=$match[1][0];
                //preg_match_all('/tkn=["\']?([\d\w\W]+)?["\'];/si', $text, $match);
                $Token=$token;
                /* preg_match_all('/<input[\s]*type="hidden"[\s]*name="cgnr"[\s]*id="cgnr"[\s]*value="?([^>]*)?"/si', $text, $match);
                $cgnr=$match[1][0];
                preg_match_all('/<input[\s]*type="hidden"[\s]*name="wasup"[\s]*id="wasup"[\s]*value="?([^>]*)?"/si', $text, $match); */
                preg_match_all('/[\s]*name=["\']wasup["\'][\s]*id=["\']wasup["\'][\s]*value=["\']?([^>]*)?["\']/si'$text$match);
                if(!isset($match[1][0]))
                    preg_match_all('/name=["\']wasup["\'][\s]*id=["\']wasup["\'][\s]*><option value=["\']?([^>]*)?["\']/si'$text$match);
                if(!isset($match[1][0]))
                    preg_match_all('/[\s]*name=["\']wasup["\'][\s]*id=["\']wasup["\'][\s]*>?([^>]*)?</si'$text$match);
                $wasup=$match[1][0];
                
                preg_match_all('/[\s]*name=["\']nrc["\'][\s]*id=["\']nrc["\'][\s]*value=["\']?([^>]*)?["\']/si'$text$match);
                if(!isset($match[1][0]))
                    preg_match_all('/name=["\']nrc["\'][\s]*id=["\']nrc["\'][\s]*><option value=["\']?([^>]*)?["\']/si'$text$match);
                if(!isset($match[1][0]))
                    preg_match_all('/[\s]*name=["\']nrc["\'][\s]*id=["\']nrc["\'][\s]*>?([^>]*)?</si'$text$match);
                $nrc=$match[1][0];
                preg_match_all('/[\s]*name=["\']HiddenAction["\'][\s]*value=["\']?([^>]*)?["\']/si'$text$match);
                if(!isset($match[1][0]))
                    preg_match_all('/name=["\']HiddenAction["\'].*><option value=["\']?([^>]*)?["\']/si'$text$match);
                $HiddenAction=$match[1][0];
                preg_match_all('/[\s]*name=["\']hud_pani["\'][\s]*id=["\']hud_pani["\'][\s]*value=["\']?([^>]*)?["\']/si'$text$match);
                if(!isset($match[1][0]))
                    preg_match_all('/name=["\']hud_pani["\'][\s]*id=["\']hud_pani["\'][\s]*><option value=["\']?([^>]*)?["\']/si'$text$match);
                if(!isset($match[1][0]))
                    preg_match_all('/[\s]*name=["\']hud_pani["\'].*id=["\']hud_pani["\'][\s]*>?([^>]*)?</si'$text$match);
                $hud_pani=$match[1][0];
                
                preg_match_all('/[\s]*name=["\']catnamedis["\'][\s]*id=["\']catnamedis["\'][\s]*value=["\']?([^>]*)?["\']/si'$text$match);
                $catnamedis $match[1][0];
                preg_match_all('/[\s]*id=["\']diffNo["\'][\s]*name=["\']diffNo["\'][\s]*value=["\']?([^>]*)?["\']/si'$text$match);
                $diffNo $match[1][0];
                
                /* preg_match_all('/<select[\s]*style="display: none;"[\s]*name="action"[\s]*id="action%>"[\s]*><option[\s]*value="?([^>]*)?"/si', $text, $match);
                $action = $match[1][0]; // get custid from the form fro the Action field in the post form                
                preg_match_all('/<textarea[\s]*style="display: none;"[\s]*name="Token"[\s]*id="Token">?([^>]*)?<\/textarea>/si', $text, $match);
                $Token = $match[1][0]; */
                
                $p urlencode($p);
                
                if($refurl_instantsms == 0)
                {
                    $refurl_instantsms=curl_getinfo($curlCURLINFO_EFFECTIVE_URL);
                }
            
            // Send SMS
            
                curl_setopt ($curlCURLOPT_URL"http://site".$autobalancer.".way2sms.com/jsp/stp2p.action");
                curl_setopt ($curlCURLOPT_REFERER$refurl_instantsms);
                curl_setopt ($curlCURLOPT_POST1);
                
                curl_setopt ($curlCURLOPT_POSTFIELDS"nrc=$nrc&wasup=$wasup&HiddenAction=$HiddenAction&hud_pani=$hud_pani&catnamedis=$catnamedis&$rqTok=$Token&$rqMob=$p&textArea=$msg&diffNo=$diffNo");
                curl_exec($curl);
                //var_dump(curl_getinfo($curl));
                @$sendError .= curl_error($curl);
            }
            array_push($result,"Message Sucessfully send to : " $p ". ");
        //}
        
        // Logout
        curl_setopt ($curlCURLOPT_URL"http://site".$autobalancer.".way2sms.com/jsp/logout.jsp");
        curl_setopt ($curlCURLOPT_REFERER$refurl);
        $text curl_exec($curl);    
        
        curl_close($curl);
        if (!empty($sendError)){
            return array($sendError);
        }
        return $result;
    }
    function split_for_sms($msg)
    {
        $length=strlen($msg);
        if($length <= 160)
        {
            return array(urlencode($msg));
        }
        else
        {
            preg_match_all("~.{0,153}(\s|$)~",$msg,$matches);
            $matches=array_filter($matches[0]);
            foreach($matches as $key=>$match)
                $matches[$key]=urlencode("PART-".($key+1).":".$matches[$key]);
            return $matches;
        }
    }
}


?>


Example usage of this class:

<?php 

$obj=new way2sms('myusername','mypassword');
$result=$obj->sendSMS('mobile_number','message');
echo implode('<br >',$result);

?>