Friday, 20 May 2016

Copy - Paste Image in Text View

Copy - Paste Image in Text View



Copy Image From Other View : -


- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UIPasteboard *pasteBoard=[UIPasteboard generalPasteboard];
    
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[array objectAtIndex:indexPath.row]]];
    
    [pasteBoard setData:data forPasteboardType:@"public.png"];
    
    UITextField  *myLabel= [[UITextField alloc] initWithFrame:CGRectMake(self.view.frame.size.width /2 - 103 , self.view.frame.size.height - 50 , 206 , 25)];
    
    myLabel.text = @"Sticker Copied";
    
    myLabel.borderStyle = UITextBorderStyleRoundedRect ;
    
    myLabel.textColor = [UIColor whiteColor];
    
    myLabel.backgroundColor = [UIColor blackColor];
    
    [self.view addSubview:myLabel];
    
    myLabel.hidden = NO;
    
    myLabel.alpha = 0.8f;
    
    [UIView animateWithDuration:0.5 delay:2.0 options:0 animations:^{
       
        myLabel.alpha = 0.0f;
    } completion:^(BOOL finished) {
       
        myLabel.hidden = YES;
    }];
    
    return NO ;
}





Paste Image In Text View : -



#import "ViewController.h"


@interface ViewController ()
{
    UITextView *textView ;
}
@end

@implementation ViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    textView = [[UITextView alloc] initWithFrame:CGRectMake(50,50,250,500)];
    
/*    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"before after"];
    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
    textAttachment.image = [UIImage imageNamed:@"1.png"];
    
    CGFloat oldWidth = textAttachment.image.size.width;
    

    CGFloat scaleFactor = oldWidth / (textView.frame.size.width - 10);
    textAttachment.image = [UIImage imageWithCGImage:textAttachment.image.CGImage scale:scaleFactor orientation:UIImageOrientationUp];
    NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
    [attributedString replaceCharactersInRange:NSMakeRange(6, 1) withAttributedString:attrStringWithImage];
    textView.attributedText = attributedString;
    */
    
    [self.view addSubview:textView];
    
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(paste:) && [UIPasteboard generalPasteboard].image)
        return YES;
    else
        return [super canPerformAction:action withSender:sender];
}


- (void)paste:(id)sender{
    
    UIImage *image = [UIPasteboard generalPasteboard].image;
    
    if (image)
    {
        NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
        textAttachment.image = image;
        NSAttributedString *imageString = [NSAttributedString attributedStringWithAttachment:textAttachment];
        
        NSAttributedString *attString =  textView.attributedText ;
        
        NSMutableAttributedString *result = [attString mutableCopy];
        [result appendAttributedString:imageString];
        
        textView.attributedText = result;
        
    } else {
        // Call the normal paste action
        [super paste:sender];
    }
}


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

@end


Friday, 6 May 2016

In - App Purchase

In - App Purchase


1) Import Storekit Framework :

-StoreKit.framework


Note :- Turn This ON 



in-app purchase tutorial

2) Create This Four File In Project :


IAPHelper ( NSObject File ) 

IAPHelper.h :


#import <StoreKit/StoreKit.h>

UIKIT_EXTERN NSString *const IAPHelperProductPurchasedNotification;

typedef void (^RequestProductsCompletionHandler)(BOOL success, NSArray * products);

@interface IAPHelper : NSObject

//------------------------------------------------------------------------

- (id)initWithProductIdentifiers:(NSSet *)productIdentifiers;
- (void)requestProductsWithCompletionHandler:(RequestProductsCompletionHandler)completionHandler;
- (void)buyProduct:(SKProduct *)product;
- (BOOL)productPurchased:(NSString *)productIdentifier;
- (void)restoreCompletedTransactions;

- (void)buyProductIdentifier:(NSString *)productIdentifier;

@end



IAPHelper.m :


// 1
#import "IAPHelper.h"
#import <StoreKit/StoreKit.h>

NSString *const IAPHelperProductPurchasedNotification = @"IAPHelperProductPurchasedNotification";

// 2
@interface IAPHelper () <SKProductsRequestDelegate, SKPaymentTransactionObserver>

@end

// 3
@implementation IAPHelper {
    SKProductsRequest * _productsRequest;
    RequestProductsCompletionHandler _completionHandler;
    
    NSSet * _productIdentifiers;
    NSMutableSet * _purchasedProductIdentifiers;
}

-(AppDelegate *)appDelegate
{
    return (AppDelegate *) [[UIApplication sharedApplication] delegate];
}

- (id)initWithProductIdentifiers:(NSSet *)productIdentifiers {

    if ((self = [super init])) {
        
        // Store product identifiers
        _productIdentifiers = productIdentifiers;
        
        // Check for previously purchased products
        
       // _purchasedProductIdentifiers = [NSMutableSet set];
        
        _purchasedProductIdentifiers = [[NSMutableSet alloc] init];
        
        for (NSString * productIdentifier in _productIdentifiers) {
            BOOL productPurchased = [[NSUserDefaults standardUserDefaults] boolForKey:productIdentifier];
            if (productPurchased) {
                [_purchasedProductIdentifiers addObject:productIdentifier];
                NSLog(@"Previously purchased: %@", productIdentifier);
            } else {
                NSLog(@"Not purchased: %@", productIdentifier);
            }
        }
        
        // Add self as transaction observer
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        
    }
    return self;
    
}

- (void)requestProductsWithCompletionHandler:(RequestProductsCompletionHandler)completionHandler {

    // 1
    _completionHandler = [completionHandler copy];
    
    // 2
    _productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:_productIdentifiers];
    _productsRequest.delegate = self;
    [_productsRequest start];
    
}

- (BOOL)productPurchased:(NSString *)productIdentifier {
    return [_purchasedProductIdentifiers containsObject:productIdentifier];
}

- (void)buyProduct:(SKProduct *)product {
    
    NSLog(@"Buying %@...", product.productIdentifier);
    
    SKPayment * payment = [SKPayment paymentWithProduct:product];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
    
}


#pragma mark - SKProductsRequestDelegate

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    
    NSLog(@"Loaded list of products...");
    _productsRequest = nil;
    
    NSArray * skProducts = response.products;
    for (SKProduct * skProduct in skProducts) {
        NSLog(@"Found product: %@ %@ %0.2f",
              skProduct.productIdentifier,
              skProduct.localizedTitle,
              skProduct.price.floatValue);
    }
    
 //   _completionHandler(YES, skProducts);
//    _completionHandler = nil;
   

    
    if(_completionHandler)
    {
        _completionHandler(YES, skProducts);
         _completionHandler = nil;
    }
    
   
    
}

- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
    
    
    NSLog(@"Failed to load list of products.");
    _productsRequest = nil;
    
    _completionHandler(NO, nil);
    _completionHandler = nil;
    
}

#pragma mark SKPaymentTransactionOBserver

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    for (SKPaymentTransaction * transaction in transactions) {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased:
                [self completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                [self failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                [self restoreTransaction:transaction];
                
            default:
                break;
        }
    };
}



- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    NSLog(@"completeTransaction...");
    
    NSLog(@"Transaction Detail - %@" ,transaction.transactionIdentifier );

    [self appDelegate].strFotTransacionID = transaction.transactionIdentifier ;
    
    [self provideContentForProductIdentifier:transaction.payment.productIdentifier];
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}


- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
  

    
    NSLog(@"restoreTransaction...");
    
    [self provideContentForProductIdentifier:transaction.originalTransaction.payment.productIdentifier];
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

}

- (void)failedTransaction:(SKPaymentTransaction *)transaction {
    

    
    NSLog(@"failedTransaction...");
    if (transaction.error.code != SKErrorPaymentCancelled)
    {
        NSLog(@"Transaction error: %@", transaction.error.localizedDescription);
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message: transaction.error.localizedDescription delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok",nil];
        
        [alertView show];

    }
    
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

- (void)provideContentForProductIdentifier:(NSString *)productIdentifier
{
  
        [_purchasedProductIdentifiers addObject:productIdentifier];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:productIdentifier];
        [[NSUserDefaults standardUserDefaults] synchronize];
    

    [[NSNotificationCenter defaultCenter] postNotificationName:IAPHelperProductPurchasedNotification object:productIdentifier userInfo:nil];
    
}

- (void)restoreCompletedTransactions {
    
    if ([[[SKPaymentQueue defaultQueue] transactions] count]) {
        
        NSLog(@"We get very non-patient user");
        
        for (SKPaymentTransaction *transaction in [[SKPaymentQueue defaultQueue] transactions])
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    }else{
        
        [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
        
       
    }
   
    
    
    // [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
   // [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
- (void) paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue
{
    NSMutableArray *purchasedItemIDs = [[NSMutableArray alloc] init];
    NSLog(@"received restored transactions: %lu", (unsigned long)queue.transactions.count);
    for (SKPaymentTransaction *transaction in queue.transactions)
    {
        NSString *productID = transaction.payment.productIdentifier;
        [purchasedItemIDs addObject:productID];
        NSLog(@"%@",purchasedItemIDs);
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Restorepayment" object:self];
}
-(void)cancelProductRequest {
  
    
    [_productsRequest cancel];
    _productsRequest = nil;
}


- (void)buyProductIdentifier:(NSString *)productIdentifier
{
    SKMutablePayment *payment = [[SKMutablePayment alloc] init] ;
    payment.productIdentifier = productIdentifier;
    
    NSLog(@"%@",payment.productIdentifier);
    
    [[SKPaymentQueue defaultQueue] addPayment:payment];

}

@end



RageIAPHelper ( IAPHelper File ) 

RageIAPHelper.h :



#import "IAPHelper.h"

@interface RageIAPHelper : IAPHelper

+ (RageIAPHelper *)sharedInstance;

@end


RageIAPHelper.m :


#import "RageIAPHelper.h"

@implementation RageIAPHelper

+ (RageIAPHelper *)sharedInstance {
    static dispatch_once_t once;
    static RageIAPHelper * sharedInstance;
    dispatch_once(&once, ^{
   
      NSSet * productIdentifiers =  [NSSet setWithObjects@"_Your_IdentiFier_" , nil];
        sharedInstance = [[self alloc] initWithProductIdentifiers:productIdentifiers];
    });
    return sharedInstance;
}

@end



3) Write Code in AppDelegate  :


#import "RageIAPHelper.h"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

       [RageIAPHelper sharedInstance];

        return YES;
}


4) Write Code in ViewController  :



* ViewController ( Implement In-App Purchase ) 

ViewController.h :



#import "RageIAPHelper.h"
#import <StoreKit/StoreKit.h>


- (void)viewDidLoad
{
    [super viewDidLoad];

    [self reload];

}


  
-(void)viewWillAppear:(BOOL)animated
{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(productPurchased:) name:IAPHelperProductPurchasedNotification object:nil];


}


- (void)viewWillDisappear:(BOOL)animated 
{

    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}


- (void)productPurchased:(NSNotification *)notification
    [_globalObject removeActivityIndicator];
    
    NSLog(@"%@",notification.object);
    
    NSString * productIdentifier = notification.object;
    [_products enumerateObjectsUsingBlock:^(SKProduct * product, NSUInteger idx, BOOL *stop) {
        if ([product.productIdentifier isEqualToString:productIdentifier]) {
          //  [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:idx inSection:selectedIndex.row]] withRowAnimation:UITableViewRowAnimationFade];
            *stop = YES;
        }
    }];
    

    //--------------- call method Which You Want After Payment

  //  [self sendRequest] ;
    
}
- (void)reload {
    _products = nil;
   
    [[RageIAPHelper sharedInstance] requestProductsWithCompletionHandler:^(BOOL success, NSArray *products) {
        if (success) {
            _products = products;
            
        }
        
    }];
}

//--------------- 3 Methods Of Payment Here

1 )


- (IBAction)paymentOK:(id)sender
{
  
        SKProduct *product;
        for (SKProduct *thisProduct in _products) {
            if ([thisProduct.productIdentifier isEqualToString:didselectCatInAppID]) {
                product = thisProduct;
            }
        }
        
         NSLog(@"Buying %@...", product.productIdentifier);
        
        [[RageIAPHelper sharedInstance] buyProduct:product];


}

2 )


- (IBAction)paymentOK:(id)sender
{
        [[RageIAPHelper sharedInstance] buyProductIdentifier:didselectCatInAppID];   

}


3 )


- (IBAction)paymentOK:(id)sender
{


            SKProduct * product = (SKProduct *) _products[0];
        
        NSLog(@"Buying %@...", product.productIdentifier);
        [[RageIAPHelper sharedInstance] buyProduct:product];


}