Archive for the ‘Coding’ Category

Check if Push Notification is enabled

We had our own flow of app permissions to be presented through our UX. Push notification was one of the permissions. For an early and simple start, my requirement was to know if an app has the permission for push notification. I used following code:

[[UIApplication sharedApplication] isRegisteredForRemoteNotifications]

Result was different on simulator and real device. On simulator it always returned NO, while it worked well on device until iOS 10.

Next, the reliable way(example) that I learned and worked across was:

- (BOOL)isPushNotificationsEnabled {
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]) {
        UIUserNotificationType types = [[[UIApplication sharedApplication] currentUserNotificationSettings] types];
        return (types & UIUserNotificationTypeAlert);
    }
    else {//Before iOS8
        UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        return (types & UIRemoteNotificationTypeAlert);
    }
}

iOS Location Services: Authorization

We may want to know about the permission for location services that is granted to the app. This is useful in many ways where you want to control the flow in your UX to show the permission at definite point of place.

General setting of location service may be OFF on device. First (optional) step would be to check if location service is ON/OFF for the device.

[CLLocationManager locationServicesEnabled]

If service is OFF/Disabled in device then you can ask for the permission based on your need:

[self.locationManager requestWhenInUseAuthorization]
[self.locationManager requestAlwaysAuthorization]

This will open default alert where user has the option to go directly to settings page of location service in a device, user can toggle service to ON/OFF, for the case where location is disabled in a device.

If location service is ON then it doesn’t mean that app has the permission to use the service. We need to check the authorisation status for the app.


[CLLocationManager authorizationStatus]

It returns the following authorization statuses:

typedef enum {
   kCLAuthorizationStatusNotDetermined = 0,
   kCLAuthorizationStatusRestricted,
   kCLAuthorizationStatusDenied,
   kCLAuthorizationStatusAuthorized,
   kCLAuthorizationStatusAuthorizedAlways = kCLAuthorizationStatusAuthorized,
   kCLAuthorizationStatusAuthorizedWhenInUse 
} CLAuthorizationStatus;

If user hasn’t given the permission yet, including denied permission, then we will get:
kCLAuthorizationStatusNotDetermined
Now we can make the permission request based on our type of need to bring the default native permission alert to the user.

[self.locationManager requestWhenInUseAuthorization]
[self.locationManager requestAlwaysAuthorization]

If user had previously denied by cancelling the permission alert then status will be kCLAuthorizationStatusDenied


In this situation we would like the app to redirect user to app’s settings in device. We may also like to show the alert manually where, once the permission is denied then default alert from iOS will not appear after asking for the permission in code, user will have the option to cancel or redirect to settings.

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];

Bugs are your friends!

A pulse of the body was synced with a blinking cursor on unfamiliar editor opened in screen. Eyes were scrutinizing the cursor as if something will pop out from there. Like the new file in editor mind too was clean not knowing what to supply it with, and then slowly cramming with random drivel. That was something happened when I was writing my very first program while sitting in computer laboratory.

Coding could be intimidating for the first time but once you are accustomed to its working then its not a rough ride. “Its like riding a bicycle”. Its not necessary you will become Lance Armstrong but enough to become further curious and capable to progress in your comfortable pace. There are many obstacles on the road when riding the bicycle. One of them is Bug. A software bug: an error or flaw that causes the program to produce unexpected or incorrect result. We were afraid of bugs. As a newcomer not everyone is equipped with tools and some extraordinary wits to understand its nature for we were still in early stage of realizing the basic grammar or syntax of the language.

I had seen my friends being uncomfortable from error flags on the screen. They had no clue about what was wrong which was plausible as I also had no clue regarding nature of errors. They would delete whole code that they had written and start anew. That is the wrong approach. Do not shy away from bugs but tackle them and understand its nature. Mine approach was always to learn about the nature of a bug. Why it happened? What does error message means? Which line of code this error occurred from? Error messages may be facile, simple and sometimes ambiguous. Lots of questions and mysteries can be answered by putting some effort to understand the error.

Do not shy away from bugs but tackle them and understand its nature

When I was learning to write code, I made mistakes in my code causing compiler to flag multiple errors. I had this picture of world painted inside my mind where I was a hacker portrayed in Hollywood movies who was trying to eliminate errors from the program. With every drop of bug-count I felt closer to breaking into the system. This really gave me thrill which kept the flame burning inside me to learn all about programming. It became my passion from a challenge.

In general, there are two category of bugs: One that is logical which leads the program to give unexpected output or a crash but program runs initially. Second is wrong grammar of the programming language; where beginners make a lot of mistake. In this phase, program never runs because of wrong syntax.

Error messages may be facile, simple and sometimes ambiguous. Lots of questions and mysteries can be answered by putting some effort to understand the error.

I had a few used books on programming that I read them to understand the semantics of the language. In school I only could understand or retain the logic and rules of mathematics inside my head if I practiced them on notebook else I would simply forget it next day. It was same phenomenon for programming language. I had to write programs to understand, learn and retain it. Through fixing bugs, I was able to learn every answers on nature of error that guided me to understand the language more intimately. I could retain this in my memory for permanent so in future I would be more efficient to figure out the error and fix it. There was this indescribable inventory inside my brain where every blocks earned from fixing bugs were stored and through these blocks I was learning slowly to figure out bigger problems. I was making progress.

There was this indescribable inventory inside my brain where every blocks earned from fixing bugs were stored and through these blocks I was learning slowly to figure out bigger problems. I was making progress.

When I was learning C programming language, I used to practice on Turbo C IDE. I got it from my friend’s group who all used to write in it. It was very basic GUI based editor and more than enough for novice like me. There are plentiful examples of mistakes I had made.

  • I forgot to put semicolon in the end of statements. I remember compiler always showed the line number on error below the original line where semicolon was actually missed. I picked up that pattern very quickly. On next occasion whenever semicolon was missed I would directly inspect the line before the number mentioned on error message.
  • One of very common mistake I made was assigning wrong data to variables. I was able to figure it out why a value belonging to a certain data type cannot be stored in variable of some other kind. This can be found in books too but again it only got retained inside head when I really tackled the devil itself.
  • There was this common error: “Lvalue required”. I learned that I was assigning some value to invalid left operand.

These elements made the foundation of grammar more strong within me.

Fixing every syntax error was my first priority. There was a time when I hardly made any syntax error, so I would go and try to fix other friend’s/classmate’s bugs (syntax related) with their permission. This helped in sharpening my debugging skills and lets me monitor my progress.

I had this picture of world painted inside my mind where I was a hacker portrayed in Hollywood movies who was trying to eliminate errors from the program.

Logical errors are tricky. Everyone has different pace, style to interpret and implement logic. But debugging logic is again laid on the foundation of your language-grammar skill. Your fluency in language and debugging syntax error definitely helps to think of constructing logic. For example, if you have learned the difference between “copy by value” and “copy by reference” then debugging the nature of logical error based on it becomes easier. You would be able to narrow it down more quickly.

Be thrilled when you encounter such errors, tackling them opens the horizon more wider. Don’t get afraid. If you needed a help then reach internet, seniors, faculty or friend but make an effort to understand the nature and property of that error. It is true that we learn from mistakes for this applies in improving debugging skills too. Better debugging skills makes you better programmer. Do not delete the code as your first solution on encounter with a bug. Sometimes you are in correct path but due to some silly error you are abandoning that and choosing another inept course.

Sometimes you are in correct path but due to some silly error you are abandoning that and choosing another inept course.

You are in a forest and trying to unite with the highway road. There may be a few thick bushes on the path but maybe the road lays just ahead of those bushes. Don’t run away from bugs. They are your friends. They will guide you to next steps of your progress. They are the guardians of new coders.

 

Tale of two Strings

Crowd of characters walked into town square;
NSString – to they belonged, everyone being aware
Of unity they held. One goes Red
And rest turned crimson blood.
Never tries out of behavior so rigid and firm,
Summon again anew for another term.
Behind came the crowd of colors many;
NSAtrributeString – to they belonged, assuming shape of any.
One thick, other tall and next blue;
Alike gang and yet flexible with choices to pursue.