Monday, February 29, 2016

Which all ports are used by Apple Push Notification service?

Push providers, iOS devices, and Mac computers are often behind firewalls. To send notifications, you will need to allow inbound and outbound TCP packets over port 2195. To reach the feedback service, you will need to allow inbound and outbound TCP packets over port 2196. Devices and computers connecting to the push service over Wi-Fi will need to allow inbound and outbound TCP packets over port 5223.
    
    The IP address range for the push service is subject to change; the expectation is that providers will connect by hostname rather than IP address. The push service uses a load balancing scheme that yields a different IP address for the same hostname. However, the entire 17.0.0.0/8 address block is assigned to Apple, so you can specify that range in your firewall rules.

    
We can Try running a telnet command on your server to see if the server can reach APNs, like this:

$ telnet 1-courier.push.apple.com 5223
$ telnet gateway.sandbox.push.apple.com 2195
$ telnet gateway.push.apple.com 2195

References:
https://developer.apple.com/library/ios/technotes/tn2265/_index.html#//apple_ref/doc/uid/DTS40010376-CH1-TNTAG41

What are main APNS message headers

For sending APNS notifications, most of us rely on the third party libraries such as JavaPNS or pushy etc. Internally, these libraries are dealing with APS to send the notifications, 
Below are the main headers when communicating with the APS 

apns-id : A canonical UUID that identifies the notification. If there is an error sending the notification, APNs uses this value to identify the notification to your server.
    The canonical form is 32 lowercase hexadecimal digits, displayed in five groups separated by hyphens in the form 8-4-4-4-12. An example UUID is as follows:
    123e4567-e89b-12d3-a456-42665544000
    If you omit this header, a new UUID is created by APNs and returned in the response. 

apns-expiration : A UNIX epoch date expressed in seconds (UTC). This header identifies the date when the notification is no longer valid and can be discarded.
    If this value is nonzero, APNs stores the notification and tries to deliver it at least once, repeating the attempt as needed if it is unable to deliver the notification the first time. If the value is 0, APNs treats the notification as if it expires immediately and does not store the notification or attempt to redeliver it.

apns-priority : The priority of the notification. Specify one of the following values:
    10–Send the push message immediately. Notifications with this priority must trigger an alert, sound, or badge on the target device. It is an error to use this priority for a push notification that contains only the content-available key.
    5—Send the push message at a time that takes into account power considerations for the device. Notifications with this priority might be grouped and delivered in bursts. They are throttled, and in some cases are not delivered.
    If you omit this header, the APNs server sets the priority to 10.

content-length : The length of the body content. You must provide a value for this header, and the body length must be less than or equal to 4096 bytes. 

apns-topic  : The topic of the remote notification, which is typically the bundle ID for your app. The certificate you create in Member Center must include the capability for this topic.
If your certificate includes multiple topics, you must specify a value for this header.
If you omit this header and your APNs certificate does not specify multiple topics, the APNs server uses the certificate’s Subject as the default topic.

References:

Swift or Objective C - another 5 points to note

1. Swift is faster : 
Swift is nearly on par with C++ for both the FFT and Mandelbrot algorithms. According to Primate Labs, the GEMM algorithm performance suggests the Swift compiler cannot vectorize code the C++ compiler can -- an easy performance gain that could be achieved in the next version of Swift. According to Primate Labs, makers of the popular GeekBench performance tool, Swift was approaching the performance characteristics of C++ for compute-bound tasks in December 2014 using the Mandelbrot algorithm.In February 2015, Primate Labs discovered that the Xcode 6.3 Beta improved Swift’s performance of the GEMM algorithm -- a memory-bound algorithm with sequential access of large arrays -- by a factor of 1.4

Dropping legacy C conventions has greatly improved Swift under the hood. Benchmarks for Swift code performance continue to point to Apple’s dedication to improving the speed at which Swift can run app logic.

2. Fewer name collisions with open source projects 
One issue that has plagued Objective-C code is its lack of formal support for namespaces, which was C++’s solution to code filename collisions. When this name collision happens in Objective-C, it is a linker error, and the app can’t run. Swift provides implicit namespaces that allow the same code file to exist across multiple projects without causing a build failure and requiring names like NSString (Next Step -- Steve Jobs’ company after being fired from Apple) or CGPoint (Core Graphics). 

3. Swift support dynamic libraries 
Dynamic libraries have never been supported on iOS until the launch of Swift and iOS 8, even though dynamic libraries have been supported on Mac for a very long time. Dynamic libraries are external to the app executable, but are included within the app bundle downloaded from the App Store. It reduces the initial size of an app as it is loaded into memory, since the external code is linked only when used.

The ability to defer loading in a mobile app or an embedded app on Apple Watch will improve the perceived performance to the user. This is one of the distinctions that make the iOS ecosystem feel more responsive. Apple has been focused on loading only assets, resources, and now compiled and linked code on the fly. The on-the-fly loading reduces initial wait times until a resource is actually needed to display on the screen.

Dynamic libraries are executable chunks of code that can be linked to an app. This feature allows current Swift apps to link against newer versions of the Swift language as it evolves over time.

4. Swift Playgroups encourage interactive coding 
Apple has added inline code execution to Playgrounds to help programmers create a chunk of code or write an algorithm while getting feedback along the way. This feedback loop can improve the speed at which code can be written because the mental model that a traditional programmer needs can be replaced with data visualizations in Playgrounds. Programming is an iterative process, and any strain that can be reduced or used to complement the creative process will make programmers more productive and free them to solve bigger problems, rather than focusing on boring details that traditional compilers have imposed on programmers.

5. Swift is future that can influence


Swift provides the development community a direct way to influence a language that will be used to create apps, embedded systems (if Apple ever licenses an embedded framework and chip for third parties), and devices like the Apple Watch.

References:
http://www.infoworld.com/article/2920333/mobile-development/swift-vs-objective-c-10-reasons-the-future-favors-swift.html?page=2

Mageia how to open up certain port

This is fairly straightforward. From the command line, run drakfirewall. Go to Advanced and type 5060/tcp 5061/tcp and then select OK. This should open up the ports required by SIP. Check this with a port scan from another machine.







Swift or Objective C ? - 5 Points

Swift will not only supplant Objective-C when it comes to developing apps for the Mac, iPhone, iPad, Apple Watch, and devices to come, but it will also replace C for embedded programming on Apple platforms. 

1. Swift is easier to read 

Since Objective C was upgraded from C, it had to add the @ symbols for few things. Swift since entirely different background, it does avoid all of those. also, it avoids bracket based function calls. so, bye bye [[[ ]]] Method and function calls in Swift use the industry-standard comma-separated list of parameters within parentheses. The result is a cleaner, more expressive language with a simplified syntax and grammar. Swift code more closely resembles natural English, in addition to other modern popular programming languages. This readability makes it easier for existing programmers from JavaScript, Java, Python, C#, and C++ to adopt Swift into their tool chain -- unlike the ugly duckling that was Objective-C.


2. Swift is easier to maintain 
Swift drops the two-file requirement. Xcode and the LLVM compiler can figure out dependencies and perform incremental builds automatically in Swift 1.2. As a result, the repetitive task of separating the table of contents (header file) from the body (implementation file) is a thing of the past. Swift combines the Objective-C header (.h) and implementation files (.m) into a single code file (.swift).

3. Swift is safer 
In Objective-C, nothing happens if you try to call a method with a pointer variable that is nil (uninitialized). The expression or line of code becomes a no-operation (no-op), and while it might seem beneficial that it doesn’t crash, it has been a huge source of bugs. A no-op leads to unpredictable behavior, which is the enemy of programmers trying to find and fix a random crash or stop erratic behavior.

Optional types make the possibility of a nil optional value very clear in Swift code, which means it can generate a compiler error as you write bad code. This creates a short feedback loop and allows programmers to code with intention. 

To provide predictable behavior Swift triggers a runtime crash if a nil optional variable is used. This crash provides consistent behavior, which eases the bug-fixing process because it forces the programmer to fix the issue right away. The Swift runtime crash will stop on the line of code where a nil optional variable has been used. This means the bug will be fixed sooner or avoided entirely in Swift code.

4. Swift is unified with Memory management 
In Objective-C, ARC is supported within the Cocoa APIs and object-oriented code; it isn’t available, however, for procedural C code and APIs like Core Graphics. This means it becomes the programmer’s responsibility to handle memory management when working with the Core Graphics APIs and other low-level APIs available on iOS. Because ARC in Swift works across both procedural and object-oriented code, it requires no more mental context switches for programmers, even as they write code that touches lower-level APIs -- a problem with the current version of Objective-C.

5. Swift require less code 
Swift reduces the amount of code that is required for repetitive statements and string manipulation. For e.g. it supports + operator for adding two strings. Swift supports string interpolation, which eliminates the need to memorize tokens and allows programmers to insert variables directly inline to a user-facing string, such as a label or button title. The type inferencing system and string interpolation mitigate a common source of crashes that are common in Objective-C.

References:

What is reactive programming

In computing, reactive programming is a programming paradigm oriented around data flows and the propagation of change. This means that it should be possible to express static or dynamic data flows with ease in the programming languages used, and that the underlying execution model will automatically propagate changes through the data flow.

For example, in an imperative programming setting, a := b + c would mean that a is being assigned the result of b + c in the instant the expression is evaluated, and later, the values of b and c can be changed with no effect on the value of a.
    
However, in reactive programming, the value of a would be automatically updated based on the new values, the opposite of functional programming.

A modern spreadsheet program is an example of reactive programming. Spreadsheet cells can contain literal values, or formulas such as "=B1+C1" that are evaluated based on other cells. Whenever the value of the other cells change, the value of the formula is automatically updated.

Another example is a hardware description language such as Verilog. In this case, reactive programming allows changes to be modeled as they propagate through a circuit.

Reactive programming has foremost been proposed as a way to simplify the creation of interactive user interfaces, animations in real time systems, but is essentially a general programming paradigm.
    
For example, in a Model-view-controller architecture, reactive programming can allow changes in the underlying model to automatically be reflected in the view, and vice versa.

References:

Sunday, February 28, 2016

What is MVVM in iOS ?

So what is MVVM, exactly? Instead of focusing on the historical context of where MVVM came from, let’s take a look at what a typical iOS app looks like and derive MVVM from there:
Here we see a typical MVC setup. Models represent data, views represent user interfaces, and view controllers mediate the interactions between the two of them. Cool.



 In typical MVC applications, a lot of logic gets placed in the view controller. Some of it belongs in the view controller, sure, but a lot of it is what’s called ‘presentation logic,’ in MVVM terms – things like transforming values from the model into something the view can present, like taking an NSDate and turning it into a formatted NSString.

We’re missing something from our diagram. Something where we can place all of that presentation logic. We’re going to call this the 'view model’ – it will sit between the view/controller and the model:



This diagram accurately describes what MVVM is: an augmented version of MVC where we formally connect the view and controller, and move presentation logic out of the controller and into a new object, the view model. MVVM sounds complicated, but it’s essentially a dressed-up version of the MVC architecture that you’re already familiar with.   

References:

iOS Why user reuse Identifier with UITableView

User dequeueReusableCellWithIdentifier to speed things up. Instead of instantiating a lot of cells, you just instantiate as many as needed, i.e. as many that are visible (this is handled automatically). If scrolling to an area in the list where there are "cells" that haven't got their visual representation yet, instead of instantiating new ones, you reuse already existing ones.
        
        
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
{
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
NSLog(@"new one");
}
else
{
     NSLog(@"old one");
}

If there are different kind of cells with different visual layout etc, create a new reuse identifier for that type of cell. This design follows the methodology of object pooling.
References:

iOS auto layout Visual Format Language

Auto Layout Visual Format Language to specify common constraints, including standard spacing and dimensions, vertical layout, and constraints with different priorities. In addition, this appendix contains a complete language grammar.

Standard Space
    [button]-[textField]

Width Constraint
    [button(>=50)]

Connection to Superview
    |-50-[purpleBox]-50-|

Vertical Layout
V:[topField]-10-[bottomField]

Flush Views
    [maroonView][blueView]

Priority
    [button(100@20)]

Equal Widths
    [button1(==button2)]

Multiple Predicates
    [flexibleButton(>=70,<=100)]

A Complete Line of Layout
    |-[find]-[findNext]-[findField(>=20)]-|



The notation prefers good visualization over completeness of expressibility. Most of the constraints that are useful in real user interfaces can be expressed using visual format syntax, but there are a few that cannot. One useful constraint that cannot be expressed is a fixed aspect ratio (for example, imageView.width = 2 * imageView.height). To create such a constraint, you must use 

constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:.


If you make a syntactic mistake, an exception is thrown with a diagnostic message. For example:
    
    Expected ':' after 'V' to specify vertical arrangement
    V|[backgroundBox]|
    ^


References:

What was Apple’s view points on introducing auto layout?

This constraint-based approach to design allows you to build user interfaces that dynamically respond to both internal and external changes.

External changes occur when the size or shape of your superview changes. With each change, you must update the layout of your view hierarchy to best use the available space. Here are some common sources of external change:
    
    The user resizes the window (OS X).
    The user enters or leaves Split View on an iPad (iOS).
    The device rotates (iOS).
    The active call and audio recording bars appear or disappear (iOS).
    You want to support different size classes.
    You want to support different screen sizes.

Auto Layout is also a key component for supporting Slide Over and Split Views on the iPad.

Here are some common sources of internal change:
    
    The content displayed by the app changes.
    The app supports internationalization.
    The app supports Dynamic Type (iOS).

Finally, if your iOS app supports dynamic type, the user can change the font size used in your app. This can change both the height and the width of any textual elements in your user interface. If the user changes the font size while your app is running, both the fonts and the layout must adapt.

references:

iOS Collection View

This component gives flexibility for showing photos 



1. Grid view 
2. stack view 

extremely customizable, one can use them to make circle layouts, cover-flow style layouts, Pulse news style layouts – almost anything!

Main components of collection view area the ones below 

UICollectionView – the main view in which the content is displayed, similar to a UITableView. Like a table view, a collection view is a UIScrollView subclass.

UICollectionViewCell – similar to a UITableViewCell in a table view. These cells make up the content of the view and are added as subviews to the collection view. Cells can be created programmatically or inside Interface Builder.

Supplementary Views – if you have extra information you need to display that shouldn’t be in the cells but still somewhere within the collection view, you should use supplementary views. These are commonly used for headers or footers.

References:

Android getting resource ID by name

Sometimes, it becomes necessary to have resource ID by name of the image. Below code works great for doing this

try {
        Class res = R.drawable.class;
        Field field = res.getField("drawableName");
        int drawableId = field.getInt(null);
    }
    catch (Exception e) {
        Log.e("MyTag", "Failure to get drawable id.", e);

    }

references:
http://stackoverflow.com/questions/3042961/how-do-i-get-the-resource-id-of-an-image-if-i-know-its-name

Sunday, February 21, 2016

Blurring an image in iOS

Image 1 like this can be blurred to the one seen on the right image 2
]

Below is the code to do this.
self.imageView.image = [UIImage imageNamed:@"register_page.jpeg"];
    
    // create effect
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    
    // add effect to an effect view
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc]initWithEffect:blur];
    effectView.frame = self.view.frame;
    
    // add the effect view to the image view
    [self.imageView addSubview:effectView];
  

References:
http://stackoverflow.com/questions/17036655/ios-7-style-blur-view

Wednesday, February 17, 2016

Opening URLs in chrome



On iOS device, by default the framework will launch Safari upon calling openURL method.

Below are the launch schemes for google chrome so that we can launch the Chrome browser directly from the app.

NSURL *inputURL = ;
    NSString *scheme = inputURL.scheme;
    
    // Replace the URL Scheme with the Chrome equivalent.
    NSString *chromeScheme = nil;
    if ([scheme isEqualToString:@"http"]) {
        chromeScheme = @"googlechrome";
    } else if ([scheme isEqualToString:@"https"]) {
        chromeScheme = @"googlechromes";
    }
    
    // Proceed only if a valid Google Chrome URI Scheme is available.
    if (chromeScheme) {
        NSString *absoluteString = [inputURL absoluteString];
        NSRange rangeForScheme = [absoluteString rangeOfString:@":"];
        NSString *urlNoScheme =
        [absoluteString substringFromIndex:rangeForScheme.location];
        NSString *chromeURLString =
        [chromeScheme stringByAppendingString:urlNoScheme];
        NSURL *chromeURL = [NSURL URLWithString:chromeURLString];
        
        // Open the URL with Chrome.
        [[UIApplication sharedApplication] openURL:chromeURL];
    }

    

References:
https://developer.chrome.com/multidevice/ios/links


Sunday, February 14, 2016

Battery Level Monitoring iOS

Apple has introduced Battery Shaming feature and improved this in iOS 9.0 



The feature is available under Settings , General

Below are few notes about the battery usage in iOS 

The screen lighting up,radios trasmitting, and chips processing are the biggest single causes of power drain on iOS devices
This is the reason, it shows up “On screen” and “backgorund” as different two options.

The ways to reduce the battery option are

1. Stop background refreshes 
2. Privacy usage for location services. 

references:

iOS Specifying Web Clip icon

Developer can add web application or web link to home screen. These links are represented by icon are called web clips. 

Below are few guidelines 

1. To specify an icon for the entire web site, place an icon in PNG format in the root document folder called apple-touch-icon.png 
2. To specify an icon for single page, add link element in the web page. This also overrides the website icon 
3. To specify multiple icons for different device resolutions - for e.g. for support for both iPad and iPhone devices - add sizes attribute to each link element as follows 
"apple-touch-icon" sizes="76x76" href="touch-icon-ipad.png"
"apple-touch-icon" sizes="120x120" href="touch-icon-iphone-retina.png"
"apple-touch-icon" sizes="152x152" href="touch-icon-ipad-retina.png"

References:

Friday, February 12, 2016

Why we need to move to SHA2

In the context of SSL, the purpose of hashing is to reduce the message size (e.g. a certificate) for use with a digital signature algorithm. The hash value or message digest is then signed to allow an end user to validate the certificate and ensure it was issued by a trust certification authority. In the past we used MD5 for hashing, we now primarily using SHA-1 while beginning the transition to SHA-2 and have SHA-3 when available in the future

Hash attacks are mainly the below

1) collision  => Collision attack occurs when it is possible to find two different messages that hash to the same value. A collision attack against a CA happen at the time of certificate issuance. In past, attack against MD5, the attacker was able to create a pair of colliding messages, one of which represented the contents of benign end-entity certificate and the other of which formed the contents of malicious CA certificate. once the entity certificate was signed by CA, the attacker reused the digital signature to produce the fraudulent CA certificate. The attacker then used their CA cert to issue fraudulent end-entity certificate for any domain. Collision attacks can be mitigated by putting entropy into the certificate. which makes it difficult for the attacker to guess the exact contents of the certificate. 

2) Second premiere : In second premiere attack, a second message can be found that hashes to the same values as the given message, This allows attacker to create fraudulent certificate at any time, not just at the time of certificate issuance. SHA-1 is currently resistant to second pre-image attack. 

3) pre-image : A premiere attack is against one-way property of a hash function In a pre-image attack, a message can be determined that hashes to a given value. this could allow a password attack, where the attacker can determine the password based on hash of the password found in the database. SHA-1 is currently resistant to pre-image attacks.

Attack against hash functions are measured against the length of time required to perform a brute force attack. in which messages are selected at random and hashed until a collision or pre-image found. The time required to find a collision by brute force is approximately 2 to power n/2 where n is the bit length of the hash. to find pre-image or image, the time required is 2to power n. Based on Moors law as the devices 


references

Tuesday, February 9, 2016

What is robot.txt

The robots exclusion standard also known as robots exclusion protocol or simply robots.txt, is standard used by website to communicate with web crawlers and other web robots. The standard specifies how to inform the web robot about the areas of the website should not be processed or scanned. 

The standard is different from, but can be used with Sitemaps, a robot inclusion standard for websites. 

Each web domain should have its own robots.txt file .

Below are some samples 

 User-agent: *
Allow:

 User-agent: *
Disallow: /

  User-agent: *
Disallow: /cgi-bin/
Disallow: /tmp/
Disallow: /junk/

  User-agent: BadBot # replace 'BadBot' with the actual user-agent of the bot
    User-agent: Googlebot
Disallow: /private/

references:

Saturday, February 6, 2016

What is schema.org



schema.org is a collaborative, community activity with a mission to create, maintain and promote schemas for structured data on the internet, on the web pages, in email messages and beyond. 

Schema.org vocabulary can be used with many different encodings. including RDFas, Microdata and JSON-LD. These vocabularies cover entities, relationships between entities and actions, and can be easily be extended through a well documented extension model. Many applications from Google, Microsoft, pinerest, Yandex and others already use these vocabularies to power rich, extensible experiences. 


Schema.org is sponsored by Google, Microsoft, Yahoo and Yandex. These vocabularies are developed by an open community process using the public-schemaorg@w3.org mailing list and through Github. 

references: