iOS 8 Map Kit Obj-C : Get Users Location

Map View | User Location
Map View | User Location

iOS 8 Map Kit Obj-C : Get Users Location

In your .plist Add a new row with the key name:

NSLocationWhenInUseUsageDescription

Or

NSLocationAlwaysUsageDescription

Define the header:

#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

Update your files with following code:

ViewController.h

#import <MapKit/MapKit.h>
#import <MapKit/MKAnnotation.h>

@interface YourViewController : UIViewController <MKMapViewDelegate,  CLLocationManagerDelegate> {

}

@property(nonatomic, retain) IBOutlet MKMapView *mapView;
@property(nonatomic, retain) CLLocationManager *locationManager;

ViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.


    mapView.delegate = self;
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    #ifdef __IPHONE_8_0
    if(IS_OS_8_OR_LATER) {
         // Use one or the other, not both. Depending on what you put in info.plist
        [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager requestAlwaysAuthorization];
    }
    #endif
    [self.locationManager startUpdatingLocation];

    mapView.showsUserLocation = YES;
    [mapView setMapType:MKMapTypeStandard];
    [mapView setZoomEnabled:YES];
    [mapView setScrollEnabled:YES];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];

    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [self.locationManager startUpdatingLocation];
    NSLog(@"%@", [self deviceLocation]);

    //View Area
    MKCoordinateRegion region = { { 0.0, 0.0 }, { 0.0, 0.0 } };
    region.center.latitude = self.locationManager.location.coordinate.latitude;
    region.center.longitude = self.locationManager.location.coordinate.longitude;
    region.span.longitudeDelta = 0.005f;
    region.span.longitudeDelta = 0.005f;
    [mapView setRegion:region animated:YES];

}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}

- (NSString *)deviceLocation {
    return [NSString stringWithFormat:@"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
}

Helping, Learning, Coding 🙂

How to add an Objective-C file in your Swift Project? or How to set Objective-C bridging header?

Bridging header
Bridging header

To import a set of Objective-C files in the same app target as your Swift code, you rely on an Objective-C bridging header to expose those files to Swift. Xcode offers to create this header file when you add an Objective-C file to an existing Swift app.

If you accept, Xcode creates the header file along with the file you were creating, and names it by your product module name followed by adding “-Bridging-Header.h”.

Alternatively, you can create a bridging header yourself by choosing File > New > File > (iOS or OS X) > Source > Header File.

You’ll need to edit the bridging header file to expose your Objective-C code to your Swift code.

To import Objective-C code into Swift from the same target

  1. In your Objective-C bridging header file, import every Objective-C header you want to expose to Swift.

    For example:

        #import "XYZCustomCell.h"
        #import "XYZCustomView.h"
        #import "XYZCustomViewController.h"
    
  2. Under Build Settings, make sure the Objective-C Bridging Header build setting under Swift Compiler – Code Generation has a path to the header.

    The path should be relative to your project, similar to the way your Info.plist path is specified in Build Settings. In most cases, you should not need to modify this setting.

Any public Objective-C headers listed in this bridging header file will be visible to Swift. The Objective-C functionality will be available in any Swift file within that target automatically, without any import statements. Use your custom Objective-C code with the same Swift syntax you use with system classes.

For Example:

    let myCell = XYZCustomCell()
    myCell.subtitle = "A custom cell"

Helping, Learning, Coding 🙂

Source : Apple Documents

Update : JSON Array Parsing in Swift Language – Swift 3 – iOS 10 – Xcode 8

Swift JSON
Swift JSON

So, how to parse following type of JSON?

Create JSON Array Object :

Parse JSON Array Object :

Complete code snippet with UITableView:

Posted a gist on github.

Helping, Learning, Coding 🙂

Add Launch Screen (LaunchImage) for iPhone 6 | 6 Plus in Xcode 6 | iOS 8

Hello Developers,
Greetings for iPhone 6, 6 Plus and Xcode 6 GM Seed !!

Question is how to add launch screens for iPhone 6 and 6 Plus.

iPhone 6 Launchscreen
iPhone 6 Launchscreen

As per Apple’s Guidelines create the launch screens :

For iPhone 6: 750 x 1334 Pixels Resolution
For iPhone 6 Plus: 1242 x 2208 Pixels Resolution

You have two options :

    1. Create launch screen by LaunchScreen.xib.
Launchscreen.xib settings
Launchscreen.xib settings
    1. Add Launch Images in assets folder.
Launch Image Assets
Launch Image Assets

Finally set the Launch Screen Settings :

Launchscreen Settings
Launchscreen Settings

Happy Screening 😉

Helping, Learning, Coding 🙂

XML Parsing in Swift Language – iOS 10 – XMLParser

XML Parsing in Swift Language
XML Parsing in Swift Language

Code syntax is changed in version Swift 3. So, I have updated this article with Xcode 8 – iOS 10

Here is tutorial about how to parse the XML data in Swift Language – iOS 10 – XMLParser

Start with creating object of XMLParser

var parser = XMLParser(contentsOf: urlToSend)!
parser.delegate = self

Delegate your class with XMLParserDelegate

class ViewController: UIViewController,XMLParserDelegate {
}

Add Delegate methods

    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
    }
    
    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
    }
    
    func parser(_ parser: XMLParser, foundCharacters string: String) {
    }
    
    func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
    }

Parse the XML with following method

parser.parse()

Complete sample code:

import UIKit

class ViewController: UIViewController,XMLParserDelegate {
    
    var strXMLData:String = ""
    var currentElement:String = ""
    var passData:Bool=false
    var passName:Bool=false
    var parser = XMLParser()
    
    @IBOutlet var lblNameData : UILabel! = nil
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let url:String="http://api.androidhive.info/pizza/?format=xml"
        let urlToSend: URL = URL(string: url)!
        // Parse the XML
        parser = XMLParser(contentsOf: urlToSend)!
        parser.delegate = self
        
        let success:Bool = parser.parse()
        
        if success {
            print("parse success!")
            
            print(strXMLData)
            
            lblNameData.text=strXMLData
            
        } else {
            print("parse failure!")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
        currentElement=elementName;
        if(elementName=="id" || elementName=="name" || elementName=="cost" || elementName=="description")
        {
            if(elementName=="name"){
                passName=true;
            }
            passData=true;
        }
    }
    
    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        currentElement="";
        if(elementName=="id" || elementName=="name" || elementName=="cost" || elementName=="description")
        {
            if(elementName=="name"){
                passName=false;
            }
            passData=false;
        }
    }
    
    func parser(_ parser: XMLParser, foundCharacters string: String) {
        if(passName){
            strXMLData=strXMLData+"\n\n"+string
        }
        
        if(passData)
        {
            print(string)
        }
    }
    
    func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
        print("failure error: ", parseError)
    }
}

Code Demo on My Github. Both Swift 2.2 and Swift 3 versions are available.

Helping, Learning, Coding 🙂