List of all Iphone and Blackberry Development codes in a one click Iphone,objective C,xcode,blackberry Development,iOS Development

Friday, May 12, 2017

iOS Singleton Class


To set values, use the below code.

YourSingletonClass *sharedManager = [YourtSingletonClass sharedManager];
sharedManager.nameString =@"name";
sharedManager.emailString =@"name@domain.com";

For getting values, use the below code
YourSingletonClass *sharedManager = [YourtSingletonClass sharedManager];
NSString *nameVal=sharedManager.nameString;
NSString *emailVal=sharedManager.emailString;


/////YourSingletonClass.h class

#import

@interface YourSingletonClass : NSObject{
    NSString *nameString;
    NSString *emailString;
}

@property (nonatomic, strong) NSString *nameString;
@property (nonatomic, strong) NSString *emailString;
+ (id)sharedManager;
@end

/////YourSingletonClass.m class

#import "YourSingletonClass.h"
@implementation YourSingletonClass
@synthesize nameString;
@synthesize emailString;

+ (id)sharedManager {
    static YourSingletonClass *sharedMyManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyManager = [[self alloc] init];
    });
    return sharedMyManager;
}

- (id)init {
    if (self = [super init]) {
        self.nameString = @"";
        self.emailString = @"";
    }
    return self;
}

- (void)dealloc {
    // Should never be called, but just here for clarity really.
}
@end



Friday, May 5, 2017

ios PayFort Payment Gateway Integration

Reference https://docs.payfort.com/
NSMutableData *webDataglobal;
NSString *sdk_token;
PayFortController *payFort;
Add PayFortDelegate in .h file.

payFort = [[PayFortController  alloc]initWithEnviroment:KPayFortEnviromentSandBox];
payFort.delegate = self;
payFort.IsShowResponsePage = YES;
             
NSMutableString *post = [NSMutableString string];
[post appendFormat:@"TESTSHAINaccess_code=%@", @"accesscodeFromAdminPortal"];
[post appendFormat:@"device_id=%@",  [payFort getUDID]];
[post appendFormat:@"language=%@", @"en"];
[post appendFormat:@"merchant_identifier=%@", @"merchantIdentifierFromAdminPortal"];
post appendFormat:@"service_command=%@", @"SDK_TOKENTESTSHAIN"];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           @"SDK_TOKEN", @"service_command",
                                           @"merchantIdentifierFromAdminPortal", @"merchant_identifier",
                                           @"accesscodeFromAdminPortal", @"access_code",                                           [self sha1Encode:post],@"signature",
                                           @"en", @"language",
                                           [payFort getUDID], @"device_id",
                                           nil];
             
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
NSString *BaseDomain =@"https://sbpaymentservices.payfort.com/FortAPI/paymentApi";
NSString *urlString = [NSString stringWithFormat:@"%@",BaseDomain];
//NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%ld",[postdata length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postdata];
//NSLog(@"signal mname %@", signalNameFunction);
NSLog(@"url string %@",urlString);
NSLog(@"url post %@",tmp);
// NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request  delegate:self];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if(connection){
  webDataglobal = [NSMutableData data];
 }
else{
  NSLog(@"The Connection is null");
}




-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [webDataglobal setLength: 0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [webDataglobal appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"error %@",error);
      payFort.IsShowResponsePage = NO;
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    id collection = [NSJSONSerialization JSONObjectWithData:webDataglobal options:0 error:nil];
    NSLog(@"receive data %@",collection);
    sdk_token = collection[@"sdk_token"];
    [self launch];
    
}

- (NSString*)sha1Encode:(NSString*)input {
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    
    uint8_t digest[CC_SHA256_DIGEST_LENGTH];
    
    CC_SHA256(data.bytes, (int)data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return output;
}

-(void) launch{
    //[NSString stringWithFormat:@"%d", [self.cartResponse.amount_payable intValue]]
    NSMutableDictionary *request = [[NSMutableDictionary alloc]init];
    [request setValue:[NSString stringWithFormat:@"%d", [self.cartResponse.amount_payable intValue]*100] forKey:@"amount"];
    [request setValue:@"PURCHASE" forKey:@"command"];
    [request setValue:@"QAR" forKey:@"currency"];
    [request setValue:@"customerEmail" forKey:@"customer_email"];
    [request setValue:@"en" forKey:@"language"];
    [request setValue:[NSString stringWithFormat:@"%lld", [@(floor([[NSDate date] timeIntervalSince1970] * 1000)) longLongValue]] forKey:@"merchant_reference"];
    [request setValue:sdk_token forKey:@"sdk_token"];
    [payFort setPayFortRequest:request]; // Must Send [payFort callPayFort:self]
    
    payFort.IsShowResponsePage = YES;
    [payFort callPayFort:self];
}

- (void)sdkResult:(id)response{
    NSLog(@"Result--------%@",response);
    if([[response objectForKey:@"status"] intValue ]==14 ){
     //success
    }else{
    //fail
    }
}

ios In App Purchase

SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:@"IAP_plan_id"]];
        productsRequest.delegate = self;

        [productsRequest start];


- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    SKProduct *validProduct = nil;
    int count = [response.products count];
    if(count > 0){
        validProduct = [response.products objectAtIndex:0];
        NSLog(@"Products Available!");
        [self purchase:validProduct];
    }
    else if(!validProduct){
        NSLog(@"No products available");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Product not available" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        //this is called if your product id is not valid, this shouldn't be called unless that happens.
    }
}

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

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
    for(SKPaymentTransaction *transaction in transactions){
        switch(transaction.transactionState){
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"Transaction state -> Purchasing");
               
                //called when the user is in the process of purchasing, do not add any of your own code here.
                break;
            case SKPaymentTransactionStatePurchased:
             
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
               // NSString *receiptStr= [Base64Encoding base64EncodingForData:(transaction.transactionReceipt) WithLineLength:0];
               //Purchase success
                break;
            case SKPaymentTransactionStateRestored:
                NSLog(@"Transaction state -> Restored");
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                //called when the transaction does not finish
                if(transaction.error.code == SKErrorPaymentCancelled){
                    NSLog(@"Transaction state -> Cancelled");
                }
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                break;
        }
    }
}


//will get all the purchased plans//////
-(void)validateReceiptForTransaction
{
    /* Load the receipt from the app bundle. */
    
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receipt = [NSData dataWithContentsOfURL:receiptURL];
    
    if (!receipt) {
        /* No local receipt -- handle the error. */
    }
    
    /* ... Send the receipt data to your server ... */
    
    //NSData *receipt; // Sent to the server by the device
    
    /* Create the JSON object that describes the request */
    
    NSError *error;
    
    NSDictionary *requestContents = @{
                                      @"receipt-data": [receipt base64EncodedStringWithOptions:0]
                                      };
    
    NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents
                                                          options:0
                                                            error:&error];
    
    if (!requestData) {
        /* ... Handle error ... */
    }
    
    // Create a POST request with the receipt data.
    
    NSURL *storeURL = [NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"];
    
    NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:storeURL];
    [storeRequest setHTTPMethod:@"POST"];
    [storeRequest setHTTPBody:requestData];
    
    /* Make a connection to the iTunes Store on a background queue. */
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    [NSURLConnection sendAsynchronousRequest:storeRequest queue:queue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                               
                               if (connectionError) {
                                   
                                   /* ... Handle error ... */
                                   
                               } else {
                                   
                                   NSError *error;
                                   NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
                                   
                                   if (!jsonResponse) {
                                       /* ... Handle error ...*/
                                   }
                                   
                                   /* ... Send a response back to the device ... */
                               }
                           }];

}