Thursday, February 21, 2019

Compass

We will make a compass app.
Drag icon in to project.

Create new project, import library.
import CoreLocation
Add this line to class declaration.
 CLLocationManagerDelegate
Declare images, 5 label, variables.
let im = UIImage(named: "compass")
var ima: UIImageView!
var de = 0.0
var la:UILabel!
var la2:UILabel!
var la3:UILabel!
var la4:UILabel!
var la5:UILabel!
privatelet locationManager = CLLocationManager()

Initial, set posiotion, set text, add to view inside viewDidLoad.
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
locationManager.startUpdatingHeading()

view.backgroundColor = UIColor.whiteColor()
ima = UIImageView(frame: CGRect(x: 5, y: 110, width: 310, height: 315))
ima.image = im
la = UILabel(frame: CGRect(x: 5, y: 50, width: 95, height: 60))
la2 = UILabel(frame: CGRect(x: 55, y: 410, width: 95, height: 20))
la3 = UILabel(frame: CGRect(x: 205, y: 410, width: 95, height: 20))
la4 = UILabel(frame: CGRect(x: 132, y: 410, width: 95, height: 20))
la5 = UILabel(frame: CGRect(x: 292, y: 410, width: 95, height: 20))
la2.text = "Latitude:"
la3.text = "Longitude:"

ima.center = CGPoint(x: view.center.x, y:250)
la.center = CGPoint(x: view.center.x, y:70)

la.textColor=UIColor.blueColor()
la2.textColor=UIColor.orangeColor()
la3.textColor=UIColor.orangeColor()
la4.textColor=UIColor.orangeColor()
la5.textColor=UIColor.orangeColor()
la.font = UIFont(name:"Arial",size:32)
la.sizeToFit()
view.addSubview(ima)
view.addSubview(la)
view.addSubview(la2)
view.addSubview(la3)
view.addSubview(la4)
view.addSubview(la5)
Copy functions to above last close bracket.
func locationManager(manager: CLLocationManager, didUpdateHeading heading: CLHeading) {
de = heading.magneticHeading
la.text = String(round1(de))+gk(de)
UIView.animateWithDuration(0.0, animations: {
self.ima.transform = CGAffineTransformMakeRotation(CGFloat(360-self.de) * CGFloat(M_PI)/180)
        })
    }
func gk(degrees: Double)->String {
var l=""
if(degrees >= 337.5 || degrees <22.5) {
            l = "N"; }
if(degrees >= 22.5&& degrees <67.5) {
            l = "NE"; }
if(degrees >= 67.5&& degrees <112.5) {
            l = "E"; }
if(degrees >= 112.5&& degrees <157.5) {
            l = "SE"; }
if(degrees >= 157.5&& degrees <202.5) {
            l = "S"; }
if(degrees >= 202.5&& degrees <247.5) {
            l = "SW"; }
if(degrees >= 247.5&& degrees <292.5) {
            l = "W"; }
if(degrees >= 292.5&& degrees <337.5) {
            l = "NW"; }
return"°"+l
    }
overridefunc prefersStatusBarHidden() ->Bool {
returntrue
    }
func round1(a:Double)->Double{
let mu = pow(10.0,2.0)
let r=round(a*mu)/mu
return r
    }
func locationManager(manager: CLLocationManager,
                         didChangeAuthorizationStatus status: CLAuthorizationStatus) {
print("Authorization status changed to \(status.rawValue)")
switch status {
case .Authorized, .AuthorizedWhenInUse:
locationManager.startUpdatingLocation()
default:
locationManager.stopUpdatingLocation()
        }
    }
func locationManager(manager: CLLocationManager,
                         didFailWithError error: NSError) {
//    print ("error")
let errorType = error.code == CLError.Denied.rawValue
            ? "Access Denied": "Error \(error.code)"
let alertController = UIAlertController(title: "Location Manager Error",
                                                message: errorType, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Cancel,
                                     handler: { action in })
        alertController.addAction(okAction)
presentViewController(alertController, animated: true,
                              completion: nil)
    }
func locationManager(manager: CLLocationManager, didUpdateLocations
        locations: [CLLocation]) {
iflet newLocation = locations.last {
let latitudeString = String(format: "%g\u{00B0}",
round1(newLocation.coordinate.latitude))
la4.text = latitudeString
let longitudeString = String(format: "%g\u{00B0}",
round1(newLocation.coordinate.longitude))
la5.text = longitudeString
if newLocation.horizontalAccuracy<0 {
// invalid accuracy
return
            }
if newLocation.horizontalAccuracy>100 ||
                newLocation.verticalAccuracy>50 {
// accuracy radius is so large, we don't want to use it
return
            }

        }
    }
To get location permission, right click to file info.plist, open as, source code, copy these lines to near bottom.
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app requires access to your location</string>



When reopen app, it show an inform like this.
Press Allow. You need a actual device to see compass move.


No comments:

Post a Comment