Friday, 24 June 2016

Map Based Location Tracker for iOS

Map Based Tracker For Ios



Anything location based is really cool, and having that information displayed on a map is even better! So … lets track our location and plot it on a map :)
images
The good news about this tutorial is there is very little code! The flip side is, we will have to do some extra setup. Lets begin!
Preface: I’m still very much a beginner to Swift, and I am just sharing my journey to help out other beginners :) I’m also using Xcode beta 5 for this.

Setup

Setting up the project

1
File -> New -> Project
Then select
1
iOS -> Application -> Single View Application
Give it a name and make sure we are using the language Swift :)

Open our Main.storyboard file.

images

Show the document outline. There is a little handle in the lower left window of the storyboard to do this.

images

Highlight our View Controller for this scene, and navigate to the attributes inspector.

images

For this project, we are going to set the size to be “Retina 4-Inch Full Screen” and I’m going to set the Orientation to Portrait.

Setting up the MapKit View

Apple has already provided us with a map view. So we just need to drag one into our scene.

images


Setting up the label


We are also going to have a label to display some debug information about our location. Drag one into the scene as well.

images
Feel free to adjust the attributes in the inspector to make the label look like mine. I centered the text, gave the label 3 lines, and used the awesomely cool font ‘Helvetica Neue Thin’ with a font size of 12 (incorrectly “17.0” in screen shot).

Creating the IBOutlets


Now that we have our mapview and label, we are going to drag them into our ViewController.swift code so we can control them with code.
We want to switch to assistant editor (the view that looks like a suit and bow tie in the upper right), and then “right click drag” our MKMapView into our ViewController.swift file.

images
images

We also want to right click, and drag from the Label to our ViewController.swift file.

images
images

You will see some errors, but this will go away once we fix our imports. If you are dying to fix this now, add this under import UIKit

1
2
import CoreLocation
import MapKit

Editing the info.plist


We need to add 2 keys to our info.plist file, which is located in the “Supporting Files” folder. The two keys are NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription. Right click on “Information Property List”, click Add Row, and manually enter these two keys.

Programatically Added :- 

<key>NSLocationWhenInUseUsageDescription</key>
    <string>This application requires location services to work</string>
    
    <key>NSLocationAlwaysUsageDescription</key>
    <string>This application requires location services to work</string>


images

The final form should look like this:

images


Simulating your location


The last thing I want to mention is there is no way (I saw) to have the iOS simulator aware of your actual location. However, the simulator DOES allow you to fake this data. Make sure you have a good simulation selected or else this program will just show an empty map.

Once you have the simulator going select a location!!!
images


ViewController.swift and Full Code


Phew! Thank goodness all that setup is out of the way. Time for the code!


//
//  ViewController.swift
//  UpdatePolyline_Swift
//
//  Created by INT MAC 2015 on 24/06/16.
//  Copyright © 2016 INT. All rights reserved.
//

import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController , CLLocationManagerDelegate, MKMapViewDelegate {

    
    @IBOutlet weak var theMap: MKMapView!
    @IBOutlet weak var theLabel: UILabel!
    
    var manager:CLLocationManager!
    var myLocations: [CLLocation] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        
        //Setup our Location Manager
        manager = CLLocationManager()
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestAlwaysAuthorization()
        manager.startUpdatingLocation()
        
        //Setup our Map View
        theMap.delegate = self
        theMap.mapType = MKMapType.Satellite
        theMap.showsUserLocation = true
        
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
        theLabel.text = "\(locations[0])"
        myLocations.append(locations[0] )
        
        let spanX = 0.007
        let spanY = 0.007
        var newRegion = MKCoordinateRegion(center: theMap.userLocation.coordinate, span: MKCoordinateSpanMake(spanX, spanY))
        theMap.setRegion(newRegion, animated: true)
        
        if (myLocations.count > 1){
            var sourceIndex = myLocations.count - 1
            var destinationIndex = myLocations.count - 2
            
            let c1 = myLocations[sourceIndex].coordinate
            let c2 = myLocations[destinationIndex].coordinate
            var a = [c1, c2]
            var polyline = MKPolyline(coordinates: &a, count: a.count)
            theMap.addOverlay(polyline)
        }
    }
    
    func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
        
        if overlay is MKPolyline {
            var polylineRenderer = MKPolylineRenderer(overlay: overlay)
            polylineRenderer.strokeColor = UIColor.blueColor()
            polylineRenderer.lineWidth = 4
            return polylineRenderer
        }
        return nil
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}




Wednesday, 22 June 2016

Simple GET & POST Using Swift

Simple GET & POST Using Swift ( HTTP )



Json GET :-


  override func viewDidLoad() {
        super.viewDidLoad()
        
        
        //------------------------------------------- First Method of Json GET
        


let school = NSMutableArray()
        
        let miadata = NSData(contentsOfURL: NSURL(string: "http:...../api/getallschools")!)
        
        do{
            let MyData = try NSJSONSerialization.JSONObjectWithData(miadata!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
            
            print(".........\(MyData)")
            
            let array = MyData?.valueForKey("data")?.valueForKey("school_title")
            
            school.addObjectsFromArray((array)! as! [AnyObject])
            
            print("School name: \(school)")
            
            for (var i = 0; i < school.count; i += 1)
            {
                print("Index: \(school[i])")
            }
            
            
            
        }
        catch let error as NSError
        {
            
            // error.description
            print(error.description)
        }

        


        //------------------------------------------- Second Method of Json GET
        
        /*
        let requestURL: NSURL = NSURL(string: "http://www.learnswiftonline.com/Samples/subway.json")!
        let data = NSData(contentsOfURL: requestURL)
        
        do{
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
            
            if let stations = json["stations"] as? [[String: AnyObject]]
            {
                for station in stations
                {
                    if let name = station["stationName"] as? String
                    {
                        if let year = station["buildYear"] as? String
                        {
                            print(name,year)
                        }
                    }
                }
            }
        }
        catch let error as NSError
        {
            print(error.localizedDescription)
        }
        */
                //------------------------------------------- Third Method of Json GET

                /*
        let requestURL: NSURL = NSURL(string: "http://www.learnswiftonline.com/Samples/subway.json")!
        let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(urlRequest) {
            (data, response, error) -> Void in
            
            let httpResponse = response as! NSHTTPURLResponse
            let statusCode = httpResponse.statusCode
            
            if (statusCode == 200) {
                
                do{
                    
                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
                    
                    if let stations = json["stations"] as? [[String: AnyObject]] {
                        
                        for station in stations {
                            
                            if let name = station["stationName"] as? String {
                                
                                if let year = station["buildYear"] as? String {
                                    print(name,year)
                                }
                                
                            }
                        }
                        
                    }
                    
                }catch {
                    print("Error with Json: \(error)")
                }
                
            }
            
            /*
            if (statusCode == 200) {
                print("Everyone is fine, file downloaded successfully.")
            }*/
        }
        
        task.resume()*/
       
        
    }








Json POST :-




  override func viewDidLoad() {
        super.viewDidLoad()

            //------------------------------------------- json post
        
        let request = NSMutableURLRequest(URL: NSURL(string: "YOUR_URL")!)
        request.HTTPMethod = "POST"
        let postString = "user_id=385&org_id=45"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
            guard error == nil && data != nil else {                                                          // check for fundamental networking error
                print("error=\(error)")
                return
            }
            
            if let httpStatus = response asNSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }
            
            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("responseString = \(responseString)")
        }
        task.resume()

}






Monday, 20 June 2016

json Parsing Using JSONModel

json Parsing Using JSONModel


*json GET Method & Files Already Given in Previous Demo ....

Here Below JSONModel Folder Given Below Which Have All File Of Json Post ....


Click Here To Download :-   Download


This Folder Must Be Import in Your Bundle ....


Coding Part .....




MainModel.h


#import <Foundation/Foundation.h>
#import "JSONModel.h"
#import "DataModel.h"

@interface MainModel : JSONModel

@property (strong , nonatomic) NSArray < DataModel , ConvertOnDemand > *categories ;

@end



MainModel.m



#import "MainModel.h"

@implementation MainModel

@end



DataModel.h


#import <Foundation/Foundation.h>
#import "JSONModel.h"

@protocol DataModel <NSObject>

@end

@interface DataModel : JSONModel

@property (strong , nonatomic) NSString *category_name ;

@end



DataModel.m


#import "DataModel.h"

@implementation DataModel

@end





* ViewController ( Where You Wnat To use ) 

ViewController.h :




#import <UIKit/UIKit.h>

#import "MainModel.h"
#import "DataModel.h"

@interface ViewController : UIViewController

@property (strong , nonatomic) IBOutlet UITableView *tblObj ;

//-------- MainModel Obj -------//

@property (strong , nonatomic) MainModel *obj ;


@property (nonatomic ,strong) DataModel *dataModelObj ;

@end



ViewController.m :



#import "ViewController.h"
#import "NSURLConnection_Class.h"

@interface ViewController () < NSURLConnection_CustomDelegate>

@end

@implementation ViewController
@synthesize obj, dataModelObj, tblObj ;

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self getHomeData];
    
}


#pragma mark - Get Data from Json

-(void)getHomeData
{
    //---------------------- Request for Getting School List  ----------------------//
    

    NSURLConnection_Class *objURL = [[NSURLConnection_Class alloc] init] ;
    [objURL RequestForURL:@"Your URL"];
    objURL.delegate = self ;
    
}

#pragma mark - Custom Delegate [ NSURLConnection ]

-(void)connectionFailWithError:(NSError *)error
{
    NSLog(@"Error: %@",error.localizedDescription) ;
}

-(void)connectionFinishWithResponse:(NSString *)responseString
{
    NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil] ;
    
    NSLog(@"%@",responseDict);
    
    obj = [[MainModel alloc] initWithDictionary:responseDict error:nil] ;
    
    for (int i = 0; i < obj.categories.count; i ++)
    {
        dataModelObj = obj.categories[i] ;
    }
    
    [tblObj reloadData];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return obj.categories.count ;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tblObj dequeueReusableCellWithIdentifier:@"cell"];
    
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"] ;
    }
    
    dataModelObj = obj.categories[indexPath.row] ;
    
    cell.textLabel.text = dataModelObj.category_name ;
    
    return cell ;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end