Sunday, 24 July 2016

How to place a UICollectionView inside a UITableViewCell

Please find the project at below link:


https://github.com/iossolutions/examples

Enjoy :)

UIColor extension random color Swift

extension UIColor {
    class func randomColor() -> UIColor {
        let hueAmount = CGFloat(arc4random() % 100) / 100
        let saturationAmount = CGFloat(arc4random() % 100) / 100
        let brightnessAmount = CGFloat(arc4random() % 100) / 100
        return UIColor(hue: hueAmount, saturation: saturationAmount, brightness: brightnessAmount, alpha: 1.0)
    }

}

Friday, 22 July 2016

To covert all english numerics to arabic numerics inside a text , iOS Swift 2.2

// To covert all English numerics to arabic numerics iOS Swift 2.2

public extension String
{

 private static let numberFormatter: NSNumberFormatter = {
        let numberFormatter = NSNumberFormatter()
        return numberFormatter
    }()


public var localizedTextForNumber: String {
        var text = self ?? ""
        var numArray: [String] = []
        var locArray: [NSNumber] = []
        let scanner: NSScanner = NSScanner(string:text)
        let numbers: NSCharacterSet = NSCharacterSet(charactersInString: "0123456789")
        while scanner.atEnd == false {
            var buffer: NSString?
            if scanner.scanCharactersFromSet(numbers, intoString: &buffer) {
                numArray.append((buffer as? String) ?? "")
                locArray.append(scanner.scanLocation)
            }
            else {
                scanner.scanLocation = (scanner.scanLocation + 1)
            }
        }
        for (index, element) in numArray.enumerate() {
            let len = String(numArray[index]).characters.count
            let loc : Int = Int(locArray[index] ) - len
            if( (loc + len) <= text.length) {
            text.replaceRange(text.startIndex.advancedBy(loc)..<text.startIndex.advancedBy(loc + len), with: element.localizedString)
            }
        }
        if(text.length != 0){
            return text
        }
        return self

    }

public var localizedString: String {
        
        // return arabic zero if string's each element is zero
        let numberStr = self
        let language = Preferences.sharedInstance.appLanguage()
        if(language == "ar") {
            let arrayfirst = numberStr.characters.filter{$0 == "0"}
            if numberStr.characters.count ==  arrayfirst.count {
                let array = numberStr.characters.map { (value) -> String in
                    if value == "0" {
                        return "٠" // Symbol for arabic zero
                    }
                    return ""
                }
                return array.joinWithSeparator("")
            }
        }
        
        let country = Preferences.sharedInstance.appCountry()
        var locale = Preferences.sharedInstance.appLocale()
        if country == "ae" && language == "ar" {
            locale = NSLocale(localeIdentifier: "ar_SA") ?? NSLocale.currentLocale()
        }
        
        String.numberFormatter.locale = locale
        if let str = String.numberFormatter.stringFromNumber(NSNumber(double: self.doubleValue)) 
        {
            return str
        }
        return self
    }

 }

//input - "Hi I have 99 balls".localizedTextForNumber

//outPut - Hi I have ٩٩ balls

// For only numbers to convert
// input - "99".localizedString
// output - ٩٩

Tuesday, 14 June 2016

Map weather a string contains all same character or not and can also replace with other character

In This example we are replacing "0" with A, You can edit as per your requirement


let numberStr = "0000" // Here you set your string
let arrayfirst = numberStr.characters.filter{$0 == "0"}
// This is to check weather coming string is only having "0" or any other character only or not, 
            if numberStr.characters.count ==  arrayfirst.count { // If yes then this condition will satisfy
                let array = numberStr.characters.map { (value) -> String in
                    if value == "0" {
                        return "A" // Symbol for arabic zero
                    }
                    return ""
                }
                return array.joinWithSeparator("")
            }
Out Put: "AAAA"

Tuesday, 16 September 2014

To remove parent alpha from subview or child views ios

You need to just add below line of code

urUIViewObject.layer.allowsGroupOpacity = YES;    
// urUIViewObject - this is your parent view
/*
If your parent view has alpha 0.5 and you dont want your subviews to be affected by this alpha property, then use it */

Friday, 25 July 2014

Download file or zip using AFNetworking and know the progress

Include AFNetworking in your project

Include below file in your class where you are downloading something


#import "AFNetworking/AFHTTPRequestOperationManager.h"


Use below lines of code for downloading and know progress length


NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http:urPath/act01.zip"]];
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"filename"];
        operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
        
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"Successfully downloaded file to %@", path);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"Error" message:[NSString stringWithFormat:@"%@",error] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil ];
            [alert show];
        }];
        
        [operation start];
        
        [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            float progress = ((float)totalBytesRead) / totalBytesExpectedToRead;
            NSLog(@"status %f",progress);
           // self.progressView.progress = progress;

        }];

Tuesday, 20 May 2014

Replace specific string from a long text or line in iOS

 NSString *stringFromChange = [NSString stringWithFormat:@"hi this is pankaj"]];

    
stringFromChange = [stringFromChange stringByReplacingOccurrencesOfString:@"hi"

                                           withString:@"hello"];

// Now output : hello this is pankaj

HTML content in UIWebView

NSString *body =@"<html><head><title>The Meaning of Life</title></head><body><p>...really is <b>42</b>!</p></body></html>  <p style='color:red' text=\"#FFFFFF\" face=\"Bookman Old Style, Book Antiqua, Garamond\" size=\"5\"> <b> pankaj </b> <i>bhardwaj</i>  <u>test</u><img src='images_pv_tablet/4.png' width='202' height='152'>";
    
   /*
    NSString *myDescriptionHTML = [NSString stringWithFormat:@"<html> \n"
                                   "<head> \n"
                                   "<style type=\"text/css\"> \n"
                                   "body {font-family: \"%@\"; font-size: %@;}\n"
                                   "</style> \n"
                                   "</head> \n"
                                   "<body>%@</body> \n"
                                   "</html>", @"CronosPro-Regular", [NSNumber numberWithInt:fontVal], urString];

*/ // to set font

    

    
    NSData* data=[body dataUsingEncoding:NSUTF8StringEncoding];
    [NSURL URLWithString:@"nil"];
    if (data)
    {
        [urWebView loadData:data MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"nil"]];
    }
    

    urWebView.dataDetectorTypes = UIDataDetectorTypeAll;

Tuesday, 8 April 2014

Search string in array (objective-C)

//Check out below lines of code:


BOOL isObjectPresent = [yourArray containsObject: @"yourString"];
NSUInteger index = [yourArray indexOfObject: @"yourString"];

Monday, 7 April 2014

In App Purchase implementation with receipt validation from iTunes via Server side involvment

Developer just need to encode transactionReceipt into Base64 via below command:



 NSString *receipt= [transaction.transactionReceipt base64EncodedStringWithOptions:kNilOptions];
// call below method and send this string
//and then send this receipt to your server using below code.



-(void)hitLocalServerReceipt:(NSString *)receiptString
{

        NSString *new_url_new =[NSString stringWithFormat:@"http:yourLink"];
    
    //initialize url that is going to be fetched.
    NSString *strURL = [new_url_new stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:strURL];
    
    //initialize a request from url
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
    
    //set http method
    [request setHTTPMethod:@"POST"];
    //initialize a post data
    
  
    NSString *postData = [NSString stringWithFormat:@"receipt=%@",receiptString];
    
    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    //set post data of request
    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
   
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *e = nil;
        NSArray* response_arr= [NSJSONSerialization JSONObjectWithData:responseObject options: NSJSONReadingMutableContainers error: &e];
        NSLog(@"response from local server%@",response_arr);
        [self requestingDOwnload:response_arr];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"ERROR : %@",error);
         
     }];
    [operation start];
}


//Here i am using Afnetworking so dont confuse you can use NSURL connection or as per //your requirement

Thursday, 3 April 2014

In App Purchase implementation with receipt validation from iTunes through Objective - C

To implement In App Purchase we need to look around many things as follows:

1) First of all create a test account steps:

Go for     https://itunesconnect.apple.com

Enter login credentials and click on Manage users tab see below image for reference



Then click on Test user and create test account.

2) Go for Manage Your Apps and select your app click on Manage In - App Purchases.
and create a in app purchase by filling out details.

3) Now come to your Xcode create a new file and paste below code in .h file

---------------------------------------Start------------------------------------------
#import <Foundation/Foundation.h>

@protocol InAppPurchaseHandlerDelegate <NSObject>

-(void)inAppPurchaseHandlerReturnReciept:(NSData*)receipt otherResponse:(NSString*)dataResponse;

@end

@interface InAppPurchaseHandler : NSObject


+(InAppPurchaseHandler*)sharedInstance;

@property id <InAppPurchaseHandlerDelegate> delegate;


-(void)requestProduct:(NSString*)productIdentifier;
@end

----------------------------------------End-----------------------------------------

Now paste below code in your .m file

------------------------------------Start---------------------------------------------


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



@interface InAppPurchaseHandler ()<SKProductsRequestDelegate,SKPaymentTransactionObserver>

@property SKProductsRequest * productRequest;
@end

@implementation InAppPurchaseHandler


static InAppPurchaseHandler * sharedObject;


+(InAppPurchaseHandler*)sharedInstance{ 
    @synchronized(self){
        if (sharedObject==nil) {
            sharedObject=[[InAppPurchaseHandler alloc]init];
        }
    }
    return sharedObject;
}




-(void)requestProduct:(NSString*)productIdentifier{

    _productRequest= [[SKProductsRequest alloc] initWithProductIdentifiers:   [NSSet setWithObject: productIdentifier]];
    _productRequest.delegate = self;
    [_productRequest start];
}
#pragma mark - SKProductsRequestDelegate
-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    
    int coutProduct=[response.products count];
    
    if (coutProduct>0) {
        SKProduct * product = [response.products lastObject];

        NSLog(@"%@",[NSString stringWithFormat:@"Product Title: %@",product.localizedTitle]);
         NSLog(@"%@",[NSString stringWithFormat:@"Product Description: %@",product.localizedDescription]);
         NSLog(@"%@",[NSString stringWithFormat:@"Product ProductIdentifier: %@",product.productIdentifier]);
        [self makePayementForProduct:product];
    }  else{
        NSLog(@"Product not available!");
    }
    
}

-(void)request:(SKRequest *)request didFailWithError:(NSError *)SKRequest{
     NSLog(@"%@",[NSString stringWithFormat:@"SKRequest SKRequest: %@",SKRequest.localizedDescription]);
  
    NSString* transactionState =[NSString stringWithFormat:@"%@",SKRequest.localizedDescription];
    [self.delegate inAppPurchaseHandlerReturnReciept:nil otherResponse:transactionState];
}



-(void)makePayementForProduct:(SKProduct*)product{
    SKPayment * payment =[SKPayment paymentWithProduct:product];
    [[SKPaymentQueue defaultQueue]addTransactionObserver:self];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}





-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
    
    
    NSData * transactionReceipt=nil;
    
    for (SKPaymentTransaction * transaction in transactions) {
        
        
        
        switch (transaction.transactionState) {
                
            case SKPaymentTransactionStatePurchasing:
                transactionReceipt=transaction.transactionReceipt;
                NSLog(@"%@ transactionReceipt %@",transaction.transactionReceipt,transactionReceipt);
                break;
            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...");

    NSString *base64TxReceiptStr = [self base64forData:transaction.transactionReceipt];

    NSDictionary *command = [NSDictionary dictionaryWithObjectsAndKeys:
                             base64TxReceiptStr, @"receipt-data",
                             nil];
    
    NSData* encodedData = [NSJSONSerialization dataWithJSONObject:command options:NSJSONWritingPrettyPrinted error:nil];
    
    [self.delegate inAppPurchaseHandlerReturnReciept:encodedData otherResponse:nil];
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    
    
}
- (NSString*) base64forData:(NSData*)data {
    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
    const int size = ((data.length + 2)/3)*4;
    uint8_t output[size];
    
    const uint8_t* input = (const uint8_t*)[data bytes];
    for (int i = 0; i < data.length; i += 3)
    {
        int value = 0;
        for (int j = i; j < (i + 3); j++)
        {
            value <<= 8;
            if (j < data.length)
                value |= (0xFF & input[j]);
        }
        
        const int index = (i / 3) * 4;
        output[index + 0] =  table[(value >> 18) & 0x3F];
        output[index + 1] =  table[(value >> 12) & 0x3F];
        output[index + 2] = (i + 1) < data.length ? table[(value >> 6)  & 0x3F] : '=';
        output[index + 3] = (i + 2) < data.length ? table[(value >> 0)  & 0x3F] : '=';
    }
    
    return  [[NSString alloc] initWithBytes:output length:size encoding:NSASCIIStringEncoding];
}

- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
    NSLog(@"restoreTransaction...");
    
   
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

- (void)failedTransaction:(SKPaymentTransaction *)transaction {
    
    NSLog(@"failedTransaction...");
    if (transaction.error.code != SKErrorPaymentCancelled)
    {
        NSLog(@"Transaction error: %@", transaction.error.localizedDescription);
    }
    
    NSString* transactionState =@"failed";
    [self.delegate inAppPurchaseHandlerReturnReciept:nil otherResponse:transactionState];
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}




-(void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue{
    
    
    
}
@end

-------------------------------------End--------------------------------------------


4) Now include above class to your class where you are want to perform this action as follows call belw method named inappHit :

-(void)inappHit:(UIButton*)sender
{
    // i am using 105 as a product key change it as required

    NSString *productIdentifier=[NSString stringWithFormat:@"105"];
    [InAppPurchaseHandler sharedInstance].delegate=self;
    [[InAppPurchaseHandler sharedInstance]requestProduct:productIdentifier];
}

// delegate function
-(void)inAppPurchaseHandlerReturnReciept:(NSData *)receipt otherResponse:(NSString *)dataResponse
{
    //receipt    
    NSLog(@"receipt %@",receipt);
    
    if ([[NSString stringWithFormat:@"%@",receipt] isEqualToString:@"(null)"])
    {
    [alert_itunes_connecting dismissWithClickedButtonIndex:0 animated:YES];
       alert_itunes_connecting= [[UIAlertView alloc]initWithTitle:dataResponse message:nil delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil  , nil];
        [alert_itunes_connecting show];
    }else
    {
       [self hitLocalServerReceipt:receipt];
    }
}


//  itunes hit for receipt validation
-(void)hitLocalServerReceipt:(NSData *)receiptString
{

// NOTE: use "buy" vs "sandbox" in production.


    NSMutableURLRequest *txReceiptVerificationRequest=[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"]];
    [txReceiptVerificationRequest setHTTPBody:receiptString];
    [txReceiptVerificationRequest setHTTPMethod:@"POST"];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:txReceiptVerificationRequest];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *e = nil;
        NSArray* array= [NSJSONSerialization JSONObjectWithData:responseObject options: NSJSONReadingMutableContainers error: &e];
        NSLog(@"response from iTunes%@",array); // your response
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"ERROR : %@",error);
         
     }];
    [operation start];
}