Tuesday, 3 November 2015

Custom Calender & Save Data

Custom Calender & Save Data


1) Import Following Framework :

EventKit.Framework

************** Create NSObject File And Write Following Coding **********

2) Create Custom NSObject File  :

MyCalendar.h :

#import <Foundation/Foundation.h>

@interface MyCalendar : NSObject


+ (void)requestAccess:(void (^)(BOOL granted, NSError *error))success;
+ (BOOL)addEventAt:(NSDate*)eventDate withEndDate:(NSDate*)endDate withTitle:(NSString*)title inLocation:(NSString*)location latitude: (NSString*)latval longitude:(NSString*)longval ;
+ (BOOL)removeEventAt:(NSDate*)eventDate withEndDate:(NSDate*)endDate withTitle:(NSString*)title inLocation:(NSString*)location;



@end


MyCalendar.m :

#import "MyCalendar.h"
#import <EventKit/EventKit.h>

static EKEventStore *eventStore = nil;
static NSString *savedEventId;

@implementation MyCalendar


+ (void)requestAccess:(void (^)(BOOL granted, NSError *error))callback;
{
    if (eventStore == nil) {
        eventStore = [[EKEventStore alloc] init];
    }
    // request permissions
    [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:callback];
}


+ (BOOL)addEventAt:(NSDate*)eventDate withEndDate:(NSDate*)endDate withTitle:(NSString*)title inLocation:(NSString*)location latitude: (NSString*)latval longitude:(NSString*)longval ;
{
    EKEvent *event = [EKEvent eventWithEventStore:eventStore];
    EKCalendar *calendar = nil;
    NSString *calendarIdentifier = [[NSUserDefaults standardUserDefaults] valueForKey:@"my_calendar_identifier"];

    // when identifier exists, my calendar probably already exists
    // note that user can delete my calendar. In that case I have to create it again.
    if (calendarIdentifier) {
        calendar = [eventStore calendarWithIdentifier:calendarIdentifier];
    }
    
    // calendar doesn't exist, create it and save it's identifier
    if (!calendar) {
      
        calendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:eventStore];
        
        // set calendar name. This is what users will see in their Calendar app
        [calendar setTitle:@"Town Post"];
        
        // find appropriate source type. I'm interested only in local calendars but
        // there are also calendars in iCloud, MS Exchange, ...
        // look for EKSourceType in manual for more options
       /* for (EKSource *s in eventStore.sources) {
            if (s.sourceType == EKSourceTypeLocal) {
                calendar.source = s;
                break;
            }
        }*/
       
        
        if (calendar.source == nil)
        {
            for (EKSource *source in eventStore.sources)
            {
               
                if (source.sourceType == EKSourceTypeCalDAV && [source.title isEqualToString:@"iCloud"])
                {
                    calendar.source = source;
                    break;
                }

                if (source.sourceType == EKSourceTypeLocal)
                {
                    calendar.source = source;
                    break;
                }
            }
        }

        
        // save this in NSUserDefaults data for retrieval later
        NSString *calendarIdentifier = [calendar calendarIdentifier];
        
        NSError *error = nil;
        BOOL saved = [eventStore saveCalendar:calendar commit:YES error:&error];
        if (saved) {
         
            // saved successfuly, store it's identifier in NSUserDefaults
            [[NSUserDefaults standardUserDefaults] setObject:calendarIdentifier forKey:@"my_calendar_identifier"];
        } else {
            // unable to save calendar
            return NO;
        }
    }
    
    // this shouldn't happen
    if (!calendar) {
        return NO;
    }
    
    // assign basic information to the event; location is optional
        event.calendar = calendar;
        event.location = location;
        event.title = title;
   
    
    // set the start date to the current date/time and the event duration to two hours
        NSDate *startDate = eventDate;
        event.startDate = startDate;
        event.endDate =  endDate;
        //event.endDate = [startDate dateByAddingTimeInterval:3600 * 2];
    
    EKStructuredLocation* structuredLocation = [EKStructuredLocation locationWithTitle:location];  // locationWithTitle has the same behavior as event.location
    CLLocation *mylocation = [[CLLocation alloc] initWithLatitude:[latval floatValue] longitude:[longval floatValue]];
    structuredLocation.geoLocation = mylocation;
    
    [event setValue:structuredLocation forKey:@"structuredLocation"];
    
    NSError *error = nil;
    // save event to the callendar
    BOOL result = [eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&error];
    
    if (result) {
        if ([event respondsToSelector:@selector(calendarItemIdentifier)]) {
            [[NSUserDefaults standardUserDefaults] setObject:event.eventIdentifier forKey:title];
            NSLog(@"Event ID: %@",event.calendarItemIdentifier);
        }
        return YES;
    } else {
       // [[NSUserDefaults standardUserDefaults] setObject:event.UUID forKey:@"eventid"];
        // unable to save event to the calendar
        return NO;
    }
}

    
+ (BOOL)removeEventAt:(NSDate*)eventDate withEndDate:(NSDate*)endDate withTitle:(NSString*)title inLocation:(NSString*)location
{
    EKEventStore *eventStore = [[EKEventStore alloc] init];
    NSLog(@"Event ID: %@",[[NSUserDefaults standardUserDefaults] objectForKey:title]);

    BOOL result;
    NSError* err = nil;
    //[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
       // if (!granted) return;
        //EKEvent* eventToRemove = [eventStore eventWithIdentifier:event.title];
    
    EKEvent *existingEvent = [eventStore eventWithIdentifier:[[NSUserDefaults standardUserDefaults] objectForKey:title]];
        if (existingEvent != nil) {
            
            result = [eventStore removeEvent:existingEvent span:EKSpanThisEvent commit:YES error:&err];
           
        }
    if (result) {
         [[NSUserDefaults standardUserDefaults] removeObjectForKey:title];
        return YES;
    } else {
         NSLog(@"Error unsave event: %@", err);
        // unable to save event to the calendar
        return NO;
    }
    
   // }];
    
    
    
    
    //EKEvent *event = [EKEvent eventWithEventStore:eventStore];
 //   EKEventStore *store = [[EKEventStore alloc] init];
   /* EKEvent *event = [EKEvent eventWithEventStore:eventStore];
    // set the start date to the current date/time and the event duration to two hours
    NSDate *startDate = eventDate;
    event.startDate = startDate;
    event.endDate =  endDate;
    //event.endDate = [startDate dateByAddingTimeInterval:3600 * 2];
    
    NSError *error = nil;
    // save event to the callendar
    BOOL result = [eventStore removeEvent:event span:EKSpanThisEvent commit:YES error:&error];
    if (result) {
        return YES;
    } else {
        // NSLog(@"Error saving event: %@", error);
        // unable to save event to the calendar
        return NO;
    }*/
    
}

@end



3) Use This Custom NSObject File In ViewController  :

- Simply Use This File At Any ViewController Using Below Coding :-

#import "MyCalendar.h"


-(NSDate *)setDateManually:(NSString *)dateStr time:(NSString *)time
{
    NSString *temp = [NSString stringWithFormat:@"%@" , dateStr] ;
    
    NSRange stringRange = {0, MIN([temp length], 10)};
    stringRange = [temp rangeOfComposedCharacterSequencesForRange:stringRange];
    
    NSString *shortString = [temp substringWithRange:stringRange];
    
    NSDateFormatter* gmtDf = [[NSDateFormatter alloc] init] ;
    
    [gmtDf setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
    [gmtDf setDateFormat:@"yyyy-MM-dd"];
    
    NSDate* gmtDate = [gmtDf dateFromString:shortString];
    
    
    
    NSRange stringRange1 = {0, MIN([time length], 5)};
    stringRange1 = [time rangeOfComposedCharacterSequencesForRange:stringRange1];
    
    NSString *shortString1 = [time substringWithRange:stringRange1];
    
    
    NSString *hourStr = [shortString1 componentsSeparatedByString:@":"][0];
    NSString *minutesStr = [shortString1 componentsSeparatedByString:@":"][1];
    
    NSString *timeSpecific = [time substringFromIndex:[time length] - 2];  //// AM , PM
    
    NSInteger hour ;
    NSInteger minutes ;
    
    
    if([timeSpecific isEqualToString:@"am"])
    {
        hour  = [hourStr intValue];
        minutes  = [minutesStr intValue];
    }
    else
    {
        hour = 12 + [hourStr intValue];
        minutes = [minutesStr intValue];
    }
    
    NSCalendar* usCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian] ;
    [usCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
    
    NSDate *d = [usCalendar dateBySettingHour:hour minute:minutes second:0 ofDate:gmtDate options:0];
    
    NSLog(@"date here : %@" , d) ;
    
    return d ;
}


************** Add Event To Calender **********

 NSDate *startDate = [self setDateManually:_startDateForCalender time:_startTimeForCalender] ;
    
    NSDate *endDate = [self setDateManually:_endDateForCalender time:_endTimeForCalender] ;
    
    [MyCalendar requestAccess:^(BOOL granted, NSError *error) {
        if (granted) {
            BOOL result = [MyCalendar addEventAt:startDate withEndDate:endDate withTitle:_selectedEventName  inLocation:_selectedEventLocation latitude:_selectedEventLatitude longitude:_selectedEventLongitude];
            if (result) {
                // added to calendar
            } else {
                // unable to create event/calendar
            }
        } else {
            // you don't have permissions to access calendars
        }
    }];


************** Remove Event From Calender **********

NSDate *startDate = [self setDateManually:_startDateForCalender time:_startTimeForCalender] ;
                
                NSDate *endDate = [self setDateManually:_endDateForCalender time:_endTimeForCalender] ;

                [MyCalendar requestAccess:^(BOOL granted, NSError *error) {
                    if (granted) {
                        BOOL result = [MyCalendar removeEventAt:startDate withEndDate:endDate withTitle:_selectedEventName  inLocation:_selectedEventLocation];
                        
                        //[MyCalendar removeEventAt:startDate withEndDate:endDate withTitle:_selectedEventName  inLocation:_selectedEventLocation];
                        if (result) {
                            // added to calendar
                        } else {
                            // unable to create event/calendar
                       }
                    } else {
                        // you don't have permissions to access calendars
                    }
                }];

Monday, 2 November 2015

Table View Using Swift

Table View Using Swift


Set up an Xcode project using the single-view application template, and make sure you opt for Swift as the language.



1) First of all Set Storyboard Like This :





2) write This Coding in Different View Controller

    Which is Given Below :


* First View Controller  :

ViewController.swift :

:- you Can Add Emojis Using (ctrl + Command + Space) -:

import UIKit

class ViewController: UIViewController {

    @IBOutlet
    var tableView: UITableView!
    
    var items: [String] = ["BMW ", "Volkswegan ", "Mercedece ","Honda City " , "Ferrari ","Hummer ","Scoda ","Lamborgini "]
    
    var image = ["bmw.jpeg","volks.jpeg","merce.jpeg","honda.jpeg","fer.jpeg","hummer.jpeg","scoda.jpeg", "lamborgini.jpeg"]

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
         return self.items.count;
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("myCell") as! myCell
        
        let stringTitle = items[indexPath.row] as String
        let strCarName = image[indexPath.row] as String
        
        cell.lbl?.text = stringTitle
        cell.img!.image=UIImage(named: strCarName)
        
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        
        
        let secondViewController = self.storyboard!.instantiateViewControllerWithIdentifier("secondViewController") as! secondView
        
        secondViewController.data = items[indexPath.row]
        
        secondViewController.cardata = image[indexPath.row]
        
        self.navigationController!.pushViewController(secondViewController, animated: true)
        
        //self.navigationController?.presentViewController(secondViewController, animated: true, completion: nil)

    }
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        // self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}



myCell.swift :


import UIKit

class myCell: UITableViewCell {
    
    @IBOutlet
    var img:UIImageView!
    
    @IBOutlet
    var lbl:UILabel!
    

}


secondViewController.swift :


import UIKit

class secondView: UIViewController {

    @IBOutlet
    var lblName: UILabel!
    
    @IBOutlet var carImg: UIImageView!
    
    internal var data:String?
   
    internal var cardata = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        lblName.text = data
        carImg.imageUIImage(named:"\(cardata)")!
        
    }

    @IBAction func back(sender: AnyObject) {
        
         self.navigationController!.popViewControllerAnimated(true)

    }
    
}


Phonegap Application

Phonegape Application


Module 1: Creating a Cordova Project

Steps

  1. Make sure you have an up-to-date version of Node.js installed on your system.    

    or You Can Download Direct Here : -  Download
  2. Open Terminal (Mac) or a Command window (Windows), and type the following command to install the Cordova CLI:
    npm install -g cordova
    
    or on a Mac: (use Terminal)
    sudo npm install -g cordova
    
    If you already have Cordova installed on your computer, make sure you upgrade to the latest version:
    npm update -g cordova
    
    or
    sudo npm update -g cordova
    
  3. Navigate (cd) to a directory where you store projects on your file system.                                example :    cd desktop
  4. Using the Cordova CLI, create a Cordova project named Workshop in a directory named workshop:
    cordova create workshop com.yourname.workshop Workshop
    
  5. Navigate to the project directory:
    cd workshop
    
  6. Add support for the iOS platform (optional)  *******  (Use only For Android) ************
    To be able to build for the iOS platform, the iOS SDK must be installed on your system. If it's not, you can skip this step and add support for another platform, or simply run the tutorial application in your browser.
    1. Make sure the iOS SDK is available on your system.
    2. On the command line, make sure you are in the workshop directory and type:
      cordova platforms add ios
      
  7. Add support for the Android platform (optional) *****  (Use only For Android) *******
    To be able to build for the Android platform, the Android SDK must be installed on your system. If it's not, you can skip this step and add support for another platform, or simply run the tutorial application in your browser.
    1. Make sure the Android SDK and the ant build tool are available on your system. The Android SDK is available here. Both the android and ant tools must be available in your path.
    2. On the command line, make sure you are in the workshop directory and type:
      cordova platforms add android
      
  8. Make sure you are in the workshop directory, and add basic plugins to your projects: (Optional)
    cordova plugin add org.apache.cordova.device
    cordova plugin add org.apache.cordova.console
    
  9. Examine the directory structure under workshop.
    • The www folder is where you will code your HTML / JavaScript application. Open the index.html file in a browser to see the default application created by the Cordova CLI.
    • The platforms folder is where Cordova will build your application for different platforms (iOS, Android, etc). The contents of this folder will be automatically generated by the Cordova CLI, and you should never edit code in that directory.
    • Plugins are installed in the plugins directory.
    • Application parameters (name, author, etc) are stored in config.xml.    
  10. Here If You Have Your www Folder for your own Project Then Replace This folder With www Folder in Project.
  11. if You Replace This Folder Then Build it using Below Command :
    cordova build ios
  12. Then prepare Project using Below Command :
    cordova prepare

Module 2: Building a Cordova Project

Building for iOS

You need the iOS SDK installed on your computer to build an iOS version of your application using the steps below.
On the command line, make sure you are in the workshop directory and type:
cordova build

   : Run Your Project :


Run Using Command :-
The project is built in the workshop/platforms/ios folder. Double-click Workshop.xcodeproj to open the project in Xcode, and run it in the emulator or on your device.
You can also run the application in the iOS emulator directly from the command line. First install ios-sim:
npm install -g ios-sim
or
sudo npm install -g ios-sim
Then run the application in the iOS emulator:
cordova emulate ios