Monday, 14 December 2015

Share Image & Video on Social Media

Share Image & Video on Social Media


1) Import Following Framework :

#import <Social/Social.h>
#import <MessageUI/MessageUI.h>

&

set :-

 <MFMailComposeViewControllerDelegate,UIDocumentInteractionControllerDelegate>



@property (retain) UIDocumentInteractionController * documentInteractionController;


2) Write This Source code in info.plist  :


<key>LSApplicationQueriesSchemes</key>
<array>
<string>instagram</string>
<string>whatsapp</string>
</array>


3) Write This code For Share Image & Video  :


************** Image & Video Share on Whatsapp **********

-(void)whatsappshare
{
    //new code
    if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"whatsapp://app"]])
    {
        
        if ([SelectedMediaType isEqualToString:@"image"])
        {
            UIImage     * iconImage = self.fullCard.image;
            NSString    * savePath  = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/whatsAppTmp.wai"];
        
            [UIImageJPEGRepresentation(iconImage, 1.0) writeToFile:savePath atomically:YES];
        
            _documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:savePath]];
            _documentInteractionController.UTI = @"net.whatsapp.image";
            _documentInteractionController.delegate = self;
        
            [_documentInteractionController presentOpenInMenuFromRect:CGRectMake(0, 0, 0, 0) inView:self.view animated: YES];
        }
        else if ([SelectedMediaType isEqualToString:@"video"])
        {
            NSString    * savePath  = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/whatsAppTmp.wam"];
            
            savePath = strVideoURL ;
            
            _documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:savePath]];
            _documentInteractionController.UTI = @"net.whatsapp.movie";
            _documentInteractionController.delegate = (id)self;
            
            [_documentInteractionController presentOpenInMenuFromRect:CGRectMake(0, 0, 0, 0) inView:self.view animated: YES];
            
        }
    }
    else
    {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"WhatsApp not installed." message:@"Your device has no WhatsApp installed." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
}


************** Image & Video Share on Instagram **********

-(void)instashare
{
    if ([SelectedMediaType isEqualToString:@"image"])
    {
        NSString* imagePath = [NSString stringWithFormat:@"%@/instagramShare.igo", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
        [[NSFileManager defaultManager] removeItemAtPath:imagePath error:nil];
        
        UIImage *instagramImage = self.fullCard.image;
        [UIImagePNGRepresentation(instagramImage) writeToFile:imagePath atomically:YES];
        // NSLog(@"Image Size >>> %@", NSStringFromCGSize(instagramImage.size));
        
        self.documentInteractionController=[UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:imagePath]];
        self.documentInteractionController.delegate = self;
        self.documentInteractionController.UTI = @"com.instagram.exclusivegram";
        [self.documentInteractionController presentOpenInMenuFromRect: self.view.frame inView:self.view animated:YES ];

    }
    else if ([SelectedMediaType isEqualToString:@"video"])
    {
        NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];
        if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
        {
            UISaveVideoAtPathToSavedPhotosAlbum(strVideoURL, nil, nil, nil);
            
            NSURL *videoFilePath = [NSURL URLWithString:strVideoURL];
            NSString *caption = @"Greetings Video";
            
            NSString* escapedString =
            [videoFilePath.absoluteString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
                
            NSString* escapedCaption =
            [caption stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
                
            NSURL *instagramURL = [NSURL URLWithString:[NSString stringWithFormat:@"instagram://library?AssetPath=%@&InstagramCaption=%@",escapedString,escapedCaption]];
            if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
            {
                    [[UIApplication sharedApplication] openURL:instagramURL];
            }
        }
    }
}

************** Image Share on facebook **********

- (void)postByFb
{
    if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
    {
        SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
        
        [controller addImage:self.fullCard.image];

        [self presentViewController:controller animated:YES completion:Nil];
    }
    else
    {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Facebook not installed." message:@"Your device has no Facebook installed." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];

    }
}

************** Image Share on Twitter **********

- (void)postByTwitter
{
    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
    {
        SLComposeViewController *tweetSheet = [SLComposeViewController
                                               composeViewControllerForServiceType:SLServiceTypeTwitter];
        [tweetSheet addImage:self.fullCard.image];
        [self presentViewController:tweetSheet animated:YES completion:nil];
    }
    else
    {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Twitter not installed." message:@"Your device has no Twitter installed." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        

    }
}

************** Image & Video Share on Mail **********

- (void)mailRqst
{
    MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
    mailComposer.mailComposeDelegate = self;
    // [mailComposer setToRecipients:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%@" , emailID_str],nil]];
    if ([MFMailComposeViewController canSendMail])
    {
        
        [mailComposer setValue:@"Greetingz - Surprise Inside!" forKey:@"subject"];
        
        if ([SelectedMediaType isEqualToString:@"image"])
        {
        
            NSData *imageData = UIImagePNGRepresentation(self.fullCard.image);
            [mailComposer addAttachmentData:imageData mimeType:@"image/png" fileName:@"Greetingz"];
        
        }
        else if ([SelectedMediaType isEqualToString:@"video"])
        {
            [mailComposer addAttachmentData:[NSData dataWithContentsOfURL:videoURL] mimeType:@"video/MOV" fileName:@"Video.MOV"];
        
            // [mailComposer setSubject:@"Greetingz - Surprise Inside!"];
       
        }
         
        [self presentViewController:mailComposer animated:YES completion:nil];
    }
    
}

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            //NSLog(@"Mail cancelled");
            break;
        case MFMailComposeResultSaved:
            //NSLog(@"Mail saved");
            break;
        case MFMailComposeResultSent:
            //NSLog(@"Mail sent");
            break;
        case MFMailComposeResultFailed:
            // NSLog(@"Mail sent failure: %@", [error localizedDescription]);
        {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error !" message:[NSString stringWithFormat:@"Error %@",[error localizedDescription]] delegate:nil cancelButtonTitle:@"dismiss" otherButtonTitles:nil, nil];
            [alert show];
        }
            break;
        default:
            break;
    }
    
    // Close the Mail Interface
    [self dismissViewControllerAnimated:YES completion:NULL];
}

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.image =  UIImage(named:"\(cardata)")!
        
    }

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

    }
    
}