Thursday, September 14, 2017

My eyes got swollen after staring at Windows 8 on Macbook Pro for a few hours

I'm using Macbook Pro 13'' late 2011. I installed Windows 8 on it several months ago. I hadn't had any problems with my eyes. 

However a few days ago, I watched a movie for a few hours at night and then i went to sleep. When I woke up in the morning, my eyes got swollen. At first, i didn't think staring at my laptop long was the culprit because my eyes had been fine for months. Then, I realized that I accidentally modified the Display profile Color Management settings. 

The cause of the problem is I changed the Device Profile under Windows Color System Defaults section to Apple RGB. Switching it back to sRGB61966-2.1 solved the issue. I couldn't see the difference between those two profiles, but Apple RGB profile did hurt my eyes.





Tuesday, September 12, 2017

My iOS app does not load the UI completely

I'm developing an iOS application using Swift 3 and Xcode 8 on MacOS Sierra. I have one UITabBarController referencing 4 view controller. Here how it looks like in Interface Builder:


The first view controller below is supposed to be loaded as home screen.


But when run the project, it looked like in the image below:


And then, I looked at the Console and saw this message:

2017-09-12 16:07:40.740 Learn Swift[15358:519952] Could not load the "ConvertIcon" image referenced from a nib in the bundle with identifier "com.vathanakmao.iosapp.Learn-Swift"


Solution

It's because I don't have the "ConvertIcon" image so I remove unset the icon for the bar item of that view controller and the view controller's view loaded completely. To unset the icon, open Interface Builder and click on the bar item at the bottom of the controller. Then, open Attributes Inspector and remove the image from the Image textbox under Bar Item section.






Sunday, September 10, 2017

Highlight or annotate your favorite places on the map view using Swift 3

My demo application is for showing how to use annotations on the map view using Swift 3 (and Xcode 8). It's very simple. When you launch the app, it will show a map and the button "My Annotations". When you tap on the button, the map will navigate to your birth place. Tap on it again, it will show my favorite place called "RUPP". The image below shows how the app looks like when your launch it.


Related classes:

- MKMapView: the map view to be shown on the screen
- MKAnnotation: the info about your location such as coordinate and title
- MKAnnotationView: use it to define how the annotation (your location) looks on the map

1. Create a single application in Xcode 


Suppose you already created the application in Xcode. There should be one View Controller in Interface Builder by default.

2. Update ViewController class as following:


import UIKit
import MapKit

class MapViewAnnotationDemoController: UIViewController, MKMapViewDelegate {
    var mapView: MKMapView!
    var myAnnotationsButton: UIButton!
    private var myAnnotations = [MKAnnotation]()
    private var currentAnnotationIndex: Int = 0
    
    override func loadView() {
        mapView = MKMapView()
        mapView.delegate = self
        view = mapView
    }
    
    override func viewDidLoad() {
        initMyAnnotationsButton()
        initMyAnnotations()
    }
    
    private func initMyAnnotationsButton() {
        myAnnotationsButton = UIButton(frame: CGRect(x: 8, y:40, width: 140, height: 20))
        myAnnotationsButton.setTitle("My Annotations", for: UIControlState.normal)
        myAnnotationsButton.backgroundColor = UIColor.green
        myAnnotationsButton.addTarget(self, action: #selector(showMyAnnotations(_:)), for: UIControlEvents.touchUpInside)
        view.addSubview(myAnnotationsButton)
    }
    
    private func initMyAnnotations() {
        let myBirthPlaceAnnotation = MKPointAnnotation()
        myBirthPlaceAnnotation.title = "My Birth Place (title)"
        myBirthPlaceAnnotation.subtitle = "My Birth Place (subtitle)"
        myBirthPlaceAnnotation.coordinate.latitude = 11.5564
        myBirthPlaceAnnotation.coordinate.longitude = 104.9282
        myAnnotations.append(myBirthPlaceAnnotation)
        
        let ruppAnnotation = MKPointAnnotation()
        ruppAnnotation.title = "RUPP (title)"
        ruppAnnotation.subtitle = "RUPP (subtitle)"
        ruppAnnotation.coordinate.latitude = 11.5690
        ruppAnnotation.coordinate.longitude = 104.8907
        myAnnotations.append(ruppAnnotation)
        
        mapView.addAnnotations(myAnnotations)
    }
    
    func showMyAnnotations(_ sender: UIButton) {
        print("\nshowMyAnnotations() called")
        
        if currentAnnotationIndex == myAnnotations.count - 1 {
            currentAnnotationIndex = 0
        } else {
            currentAnnotationIndex += 1
        }
        
        mapView.showAnnotations([myAnnotations[currentAnnotationIndex]], animated: true)
    }
    
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        print("\nmapView(viewFor) called")
        
        let pinAnnotationView = MKPinAnnotationView()
        pinAnnotationView.annotation = annotation
        pinAnnotationView.animatesDrop = true
        return pinAnnotationView
    }

}


In initMyAnnotations() method,  we called mapView.addAnnotations(myAnnotations) method. And the addAnnotations() method calls the mapView(_:MKMapView, viewFor: MKAnnotation) method of the map view's delegate to get the instance of MKAnnotationView so the map view will know how to display the annotation. The delegate is the ViewController class in this case cause it extends MKMapViewDelegate and we set mapView.delegate to self.


Wednesday, September 6, 2017

Zoom to user's location in map view using Swift 3

In this example, there is gonna be only one view controller, and I'm gonna create a map view programmatically for the view controller's view. (I'm using Xcode 8.)

Let me show you how this app works. When you launch the app in simulator, you'll see the map as shown in the image below.


Then, when you click on the My Location button (the blue one) at the top left corner of the screen, you'll get the popup below



After you click the Allow button, the map will zoom to your simulated location as shown in the following image.




1). Create a single view application in Xcode

Suppose you already created a single view application in Xcode, in which there is one view controller in Interface Builder referencing the MapViewController class (in MapViewController.swift file)

2). Add a map view as the view controller's view. 

Open MapViewController.swift file and update it as following:

import UIKit
import MapKit

class MapViewController: UIViewController {
    var mapView: MKMapView!
    
    override func loadView() {
        mapView = MKMapView()
        view = mapView
    }
}

3). Add a button to navigate to user's location


3.1. Add userLocationButton variable to the MapViewController class:

var userLocationButton: UIButton!

3.2. Override viewDidLoad() method and initialize the button in it as below:

override func viewDidLoad() {
        userLocationButton = UIButton(frame: CGRect(x: 8, y: 8, width: 100, height: 20))
        userLocationButton.setTitle("My Location", for: UIControlState.normal)
        userLocationButton.backgroundColor = UIColor.blue
        userLocationButton.addTarget(self, action: #selector(showUserLocation(_:)), for: UIControlEvents.touchUpInside)
        view.addSubview(userLocationButton)
    }

The action parameter of the addTarget() method is of type Selector struct. The Selector struct conforms to ExpressibleByStringLiteral protocol, which means that you can write a #selector expression as a value of the action parameter. The #selector expression lets you access to the selector used to access a method or to a property's getter or setter in Objective-C runtime. The value of a #selector expression is an instance of Selector type.

According to Apple's documentation, there are four types of expressions: prefix expressions, binary expressions, primary expressions, and postfix expressions. The compiler evaluates an expression and then return a value, causes side effects, or both. The #selector expression is a subtype of primary expressions.

3.3. Add the handler method for the click event of the button

func showUserLocation(_ sender: UIButton) {
}

I added this empty method just to avoid the compile-time error because the compiler will evaluate the #selector expression above and check if the method exists.

4). Detecting user's location using Core Location framework


We need to ask for user's permission to access location services. In other words, we need to request when-in-user authorization. Here is the instruction from Apple's developer documentation.


4.1. Open Info.list file in the project directory using Property List editor and add this key "Privacy - Location When In Use Usage Description" under "Information Property List" key. Its value is an additional description that will be added in the popup "Allow 'Viewtest' to access your location while you use the app?"

4.2.  Make the class MapViewController extend CLLocationManagerDelegate and then add the following fields:
    let locationManager = CLLocationManager()
    private var userLocationButtonClicked: Bool = false


4.3. Add the below code to the viewDidLoad() method after the opening bracket.
        mapView.showsUserLocation = true
    locationManager.delegate = self

Setting mapView.showsUserLocation to true tells the map view to show the user's location on the map, but the user might not see it as they might be viewing another location on the screen.

We set the property locationManager.delegate to self to implement the handler methods for the location service events in MapViewController class.

4.4. Update the showUserLocation() method as following:

func showUserLocation(_ sender: UIButton) {
        userLocationButtonClicked = true
     
        switch CLLocationManager.authorizationStatus() {
        case CLAuthorizationStatus.notDetermined, .restricted, .denied:
            locationManager.requestWhenInUseAuthorization()
        case CLAuthorizationStatus.authorizedWhenInUse, .authorizedAlways:
            requestLocation()
        }

}

Calling locationManager.requestWhenInUseAuthorization() method the first time will display a popup to ask the user for giving the app the access to the location service. Any choice the user makes, the authorization status is sent to the location manager's delegate through this method CLLocationManagerDelegate.locationManager(_:CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus).

Note that the popup won't show up next time you run the project. It seems like Xcode remembers the decision. To make it appear again, quit the simulator and remove the key "Privacy - Location When In Use Usage Description" from the Info.plist file and then run the app once. After that exit the app and add the key back and build and run the project again.

4.5. Add a handler method for the event of authorization status change

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        let authStatus = CLLocationManager.authorizationStatus()
        if authStatus == CLAuthorizationStatus.authorizedWhenInUse
            || authStatus == CLAuthorizationStatus.authorizedAlways {
            requestLocation()
        }
}

private func requestLocation() {
        // check if the location service is availalbe on that device
        if !CLLocationManager.locationServicesEnabled() {
            return
        }
     
        locationManager.requestLocation()
}

The method locationManager.requestLocation() returns immediately. It requests for user's location in a separate thread. If the request is successful, it triggers the didUpdateLocations event and stops the location services automatically (to save power).

4.6. Add a handler method for the event of location update

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if userLocationButtonClicked {
            userLocationButtonClicked = false
            zoomInLocation(locations.last!)
        }
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        if let err = error as? CLError, err.code == .denied {
            manager.stopUpdatingLocation() // cancel all pending events for getting user's location
            return
        }
}

private func zoomInLocation(_ location: CLLocation) {
        let coordinateSpan = MKCoordinateSpan(latitudeDelta: 0.001, longitudeDelta: 0.001)
       let coordinateRegion = MKCoordinateRegion(center: location.coordinate, span: coordinateSpan)
        mapView.centerCoordinate = location.coordinate
        mapView.setRegion(coordinateRegion, animated: true)
}

The mapView.setRegion() method will display the region of the user's location. MKCoordinateSpan is used to define the distance between the user's location and the area around to be displayed on the screen. The shorter distance, the closer the map zooms in.

Note that you can't detect the real location of the user using the simulator even though you enables the location services in Security & Privacy settings. The user's location is simulated by Xcode and can be modified.

Here is the complete code of MapViewController class. 


Sunday, September 3, 2017

Mac OS X Yosemite and laters hurt my eyes

I had been using MacBook Pro 13'' late 2011 for a several years by staring at the screen for all day without any problems. One day, I upgraded from OSX Lion 10.7 to OSX Yosemite 10.10 and then I got headache and eye strain after staring at the screen for about 15 minutes. When I downgraded it back to OS X Lion, the problem was gone. Obviously, the OS X version is the culprit. I then tried OSX v10.11 and macOS Sierra v10.12, and I got the same problem. After that, I bought a MacBook Air 11'' mid 2013 and I experienced the same.

At first, I thought it was because of the new UI design was too bright (not clear) and the font did not look clear so I tried to calibrate the display to make it darker and increase contrast in Accessibility. Everything was better. It was clearer and easier to see. However, the problem still existed. I even copied the Display profile (*.icc files) from OS X Lion and used it on those new OSXs but no luck.

I gave up and sticked to OS X Mavericks for a while. Note that OS X Mavericks and priors are fine. In the beginning of September 2017, I started to learn Swift 4. As Swift 4 is compatible only with OS X 10.10 and laters, I tried to make research on this problem again. I went through several forums and someone said she had the same problem but her eyes seemed to be better when she changed the Display profile to  "sRGB IEC61966-2.1". She said she couldn't see the difference when switching to that profile, but she felt better with switching to that profile. I tried it too but it didn't work. 

After that, I tried the Apple RGB profile, which I copied from Windows 8 I installed on my MacBook Pro 13'', and my eye condition seemed to be 90% better. No pain in the eyes anymore. I could star at the screen for hours. Note that the other display profiles from Windows 8 didn't solve my problem. However, I still felt a little bit fatigue and got a little bit headache though. 

To improve the fatigue eye condition, I then changed the Color Temperature in Night Shift setting to warmer may be at 40%. The headache issue resulted from small system font size. I increased it by decreasing the screen resolution from 1366x768 to 1280x720.

Overall, switching the Display profile, increasing the Color Temperature, and increasing system font size did improve my eye condition about 90% after I've tested it for a few hours. After using it for a few days, I feel my condition has 99% improved. I think my eyes is getting used to it.

Monday, August 21, 2017

Main.storyboard: Scene is unreachable due to lack of entry points and does not have an identifier for runtime access via -instantiateViewControllerWithIdentifier:.

I'm using Xcode 6.1 on Mac OS X Mavericks v10.9.5. The warning appeared when I have more than one view controllers in my story board.

To remove the warning, I set the Storyboard ID (in the Identity Inspector) for all the view controllers, which are not root view controller. The root view controller is the one with the Is Initial View Controller property checked (in Attributes Inspector).

The storyboard ID identifies the view controller within a storyboard. Storyboard ID is used when you want to programmatically access a view controller for some reasons such as switching to another view.

Got black screen when starting simulator

I'm using Xcode v6.1 on Mac OS X Mavericks v10.9.5. I'm new to iOS so i'm developing a simple app for learning. It's using two frameworks such as UI Kit and Foundation. When running my app in simulator, sometimes it worked but some other times i just showed black screen as shown in the image below.


As you can see on the title bar of the simulator, the app was built and run on iPhone 4s. Then I changed the destination device to iPhone 5 or newer, it worked. I don't know why but perhaps my application is using some classes or libraries which are not supported by iPhone 4s.

To change the running device, click on Product menu then Destination and select iPhone 5. After that, clean the project (command+shift+K), and build and run (command+R) it again.