CGEventRef KeyHandler - Xcode - Mac - objective-c

So I have an app that when you press the numbers on your keyboard on top, it normally types the symbols.
But with the app it types the numbers.
But if I run it in xcode, everything works fine, but when i open the app outside of xcode it doesn't work.
I have the newest update of mac os x and xcode.
Video:
https://youtu.be/67hRybEmJJY
Can anybody help me please?
CGEventRef KeyHandler(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
UniCharCount actualStringLength;
UniCharCount maxStringLength = 1;
UniChar chars[3];
CGEventKeyboardGetUnicodeString(event, maxStringLength, &actualStringLength, chars);
NSString *rusLetters1 = #"&";
if (chars[0] == [rusLetters1 characterAtIndex:0]) {
chars[0] = '1';
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters2 = #"é";
if (chars[0] == [rusLetters2 characterAtIndex:0]) {
chars[0] = '2';
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters3 = #"\"";
if (chars[0] == [rusLetters3 characterAtIndex:0]) {
chars[0] = '3';
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters4 = #"'";
if (chars[0] == [rusLetters4 characterAtIndex:0]) {
chars[0] = '4';
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters5 = #"(";
if (chars[0] == [rusLetters5 characterAtIndex:0]) {
chars[0] = '5';
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters6 = #"§";
if (chars[0] == [rusLetters6 characterAtIndex:0]) {
chars[0] = '6';
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters7 = #"è";
if (chars[0] == [rusLetters7 characterAtIndex:0]) {
chars[0] = '7';
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters8 = #"!";
if (chars[0] == [rusLetters8 characterAtIndex:0]) {
chars[0] = '8';
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters9 = #"ç";
if (chars[0] == [rusLetters9 characterAtIndex:0]) {
chars[0] = '9';
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters0 = #"à";
if (chars[0] == [rusLetters0 characterAtIndex:0]) {
chars[0] = '0';
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
//_________________________________________________________________________________________________________________
NSString *rusLetters11 = #"&";
if (chars[0] == '1') {
chars[0] = [rusLetters11 characterAtIndex:0];
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters12 = #"é";
if (chars[0] == '2') {
chars[0] = [rusLetters12 characterAtIndex:0];
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters13 = #"\"";
if (chars[0] == '3') {
chars[0] = [rusLetters13 characterAtIndex:0];
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters14 = #"'";
if (chars[0] == '4') {
chars[0] = [rusLetters14 characterAtIndex:0];
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters15 = #"(";
if (chars[0] == '5') {
chars[0] = [rusLetters15 characterAtIndex:0];
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters16 = #"§";
if (chars[0] == '6') {
chars[0] = [rusLetters16 characterAtIndex:0];
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters17 = #"è";
if (chars[0] == '7') {
chars[0] = [rusLetters17 characterAtIndex:0];
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters18 = #"!";
if (chars[0] == '8') {
chars[0] = [rusLetters18 characterAtIndex:0];
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters19 = #"ç";
if (chars[0] == '9') {
chars[0] = [rusLetters19 characterAtIndex:0];
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
NSString *rusLetters10 = #"à";
if (chars[0] == '0') {
chars[0] = [rusLetters10 characterAtIndex:0];
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
return event;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
CFMachPortRef eventTap;
CGEventMask eventMask;
CFRunLoopSourceRef runLoopSource;
eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, eventMask, KeyHandler, NULL);
if (!eventTap) {
exit(1);
}
runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
CGEventTapEnable(eventTap, true);
CFRunLoopRun();
}

Here's what I would do. There are many ways to calculate the modified character, this is one of them.
#import "AppDelegate.h"
#interface AppDelegate ()
#property (assign) CFMachPortRef myEventTap;
#property (assign) CFRunLoopSourceRef myRunLoopSource;
#end
#implementation AppDelegate
CGEventRef KeyHandler(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
// don't modify keys on the numeric keypad
CGEventFlags flags = CGEventGetFlags(event);
if (flags & kCGEventFlagMaskNumericPad)
return event;
// get the typed character
UniCharCount actualStringLength;
UniChar chars[3];
CGEventKeyboardGetUnicodeString(event, 3, &actualStringLength, chars);
// uncomment this line to log the typed character, the modifier flags (Shift, Option, etc.) and the key code (number of the key on the keyboard)
NSLog(#"%C %llX %lld", chars[0], flags, CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode));
if (actualStringLength == 1) {
// map the character from string1 to string2 and vice versa
NSString *string1 = #"&é\"'(§è!çà";
NSString *string2 = #"1234567890";
NSString *typedString = [NSString stringWithCharacters:chars length:1];
// find the index of the typed character in string1
NSRange range = [string1 rangeOfString:typedString];
if (range.location != NSNotFound)
// get the character in string2 at the same index
chars[0] = [string2 characterAtIndex:range.location];
else {
// find the index of the typed character in string2
range = [string2 rangeOfString:typedString];
if (range.location != NSNotFound)
// get the character in string1 at the same index
chars[0] = [string1 characterAtIndex:range.location];
}
// if the character was found, replace the character in the event
if (range.location != NSNotFound)
CGEventKeyboardSetUnicodeString(event, 1, chars);
}
return event;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// create an event tap, we want the key down and key up events
CGEventMask eventMask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp);
self.myEventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, eventMask, KeyHandler, NULL);
if (self.myEventTap) {
// create a runloop source
self.myRunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, self.myEventTap, 0);
// add it to the current run loop
CFRunLoopAddSource(CFRunLoopGetCurrent(), self.myRunLoopSource, kCFRunLoopCommonModes);
}
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// remove the event tap
if (self.myRunLoopSource) {
CFRunLoopSourceInvalidate(self.myRunLoopSource);
CFRelease(self.myRunLoopSource);
}
if (self.myEventTap)
CFRelease(self.myEventTap);
}
#end

Related

iOS 13 get application statusBar crash

only crash on beta2 and beta 3 when call code like this,:
[application valueForKeyPath:#"statusBar"]
some can help me? i call this method to get phone's network status.
the whole code like this:
if (![self isIPhoneX]) {
if ([[application valueForKeyPath:#"_statusBar"] isKindOfClass:NSClassFromString(#"UIStatusBar_Modern")]) {
children = [[[[application valueForKeyPath:#"_statusBar"] valueForKeyPath:#"_statusBar"] valueForKeyPath:#"foregroundView"] subviews];
} else {
children = [[[application valueForKeyPath:#"_statusBar"] valueForKeyPath:#"foregroundView"] subviews];
}
Class expectClass = NSClassFromString(#"UIStatusBarDataNetworkItemView");
for (id child in children) {
if ([child isKindOfClass:expectClass]) {
int netType = [[child valueForKeyPath:#"dataNetworkType"] intValue];
switch (netType) {
case 0: state = #"";break;
case 1: state = #"2g";break;
case 2: state = #"3g";break;
case 3: state = #"4g";break;
case 5: state = #"wifi";break;
default: state = #"";break;
} /* switch */
}
}
} else {
id statusBar = [application valueForKeyPath:#"statusBar"];
id statusBarView = [statusBar valueForKeyPath:#"statusBar"];
UIView *foregroundView = [statusBarView valueForKeyPath:#"foregroundView"];
children = [[foregroundView subviews][2] subviews];
for (id child in children) {
if ([child isKindOfClass:NSClassFromString(#"_UIStatusBarWifiSignalView")]) {
state = #"wifi";
}else if ([child isKindOfClass:NSClassFromString(#"_UIStatusBarStringView")]) {
NSString *str = [child valueForKeyPath:#"_originalText"];
if ([str isEqualToString:#"4G"]) {
state = #"4g";
}else if([str isEqualToString:#"3G"]){
state = #"3g";
} else{
state = #"2g";
}
}
}
}
I install iOS 13 open beta version and every thing runs good except some label showing ...,but i receive crash when online beta2 and beta3 version.
+ (NSString *)deviceNetworkingType
{
NSString *strNetworkInfo = #"No Network";
struct sockaddr_storage zeroAddress;
bzero(&zeroAddress,sizeof(zeroAddress)); zeroAddress.ss_len = sizeof(zeroAddress);
zeroAddress.ss_family = AF_INET;
// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL,(struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability,&flags);
CFRelease(defaultRouteReachability);
if(!didRetrieveFlags){ return strNetworkInfo;}
BOOL isReachable = ((flags & kSCNetworkFlagsReachable)!=0);
BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired)!=0);
if(!isReachable || needsConnection) {return strNetworkInfo;}
if((flags & kSCNetworkReachabilityFlagsConnectionRequired)== 0){
strNetworkInfo = #"WIFI";
}
if(((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0) {
if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0){
strNetworkInfo = #"WIFI";
}
}
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) ==kSCNetworkReachabilityFlagsIsWWAN) {
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
CTTelephonyNetworkInfo * info = [[CTTelephonyNetworkInfo alloc] init];
NSString *currentRadioAccessTechnology = info.currentRadioAccessTechnology;
if (currentRadioAccessTechnology) {
if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyLTE]) {
strNetworkInfo =#"4G";
} else if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS]) {
strNetworkInfo =#"2G";
} else {
strNetworkInfo =#"3G";
}
}
} else {
if((flags & kSCNetworkReachabilityFlagsReachable) == kSCNetworkReachabilityFlagsReachable) {
if ((flags & kSCNetworkReachabilityFlagsTransientConnection) == kSCNetworkReachabilityFlagsTransientConnection) {
if((flags & kSCNetworkReachabilityFlagsConnectionRequired) == kSCNetworkReachabilityFlagsConnectionRequired) {
strNetworkInfo =#"2G";
} else {
strNetworkInfo =#"3G";
}
}
}
}
}
return strNetworkInfo;
}

FFmpeg jump to most recent frame

I am looking for some help with dropping/skipping FFmpeg frames. The project I am working on streams live video which when the app goes into the background, upon returning to an active state the video stream spends a long time catching up by fast forwarding itself to the current frame. This isn't ideal and what I am aiming to achieve is have the app immediately jump to the most recent frame.
What I need to do is drop the amount of frames that are being fast-forwarded in order to catch up to the most recent frame. Is this possible? Here is my current code which decodes the frames:
- (NSArray *) decodeFrames: (CGFloat) minDuration
{
NSMutableArray *result = [NSMutableArray array];
#synchronized (lock) {
if([_reading integerValue] != 1){
_reading = [NSNumber numberWithInt:1];
#synchronized (_seekPosition) {
if([_seekPosition integerValue] != -1 && _seekPosition){
[self seekDecoder:[_seekPosition longLongValue]];
_seekPosition = [NSNumber numberWithInt:-1];
}
}
if (_videoStream == -1 &&
_audioStream == -1)
return nil;
AVPacket packet;
CGFloat decodedDuration = 0;
CGFloat totalDuration = [TimeHelper calculateTimeDifference];
do {
BOOL finished = NO;
int count = 0;
while (!finished) {
if (av_read_frame(_formatCtx, &packet) < 0) {
_isEOF = YES;
[self endOfFileReached];
break;
}
[self frameRead];
if (packet.stream_index ==_videoStream) {
int pktSize = packet.size;
while (pktSize > 0) {
int gotframe = 0;
int len = avcodec_decode_video2(_videoCodecCtx,
_videoFrame,
&gotframe,
&packet);
if (len < 0) {
LoggerVideo(0, #"decode video error, skip packet");
break;
}
if (gotframe) {
if (!_disableDeinterlacing &&
_videoFrame->interlaced_frame) {
avpicture_deinterlace((AVPicture*)_videoFrame,
(AVPicture*)_videoFrame,
_videoCodecCtx->pix_fmt,
_videoCodecCtx->width,
_videoCodecCtx->height);
}
KxVideoFrame *frame = [self handleVideoFrame];
if (frame) {
[result addObject:frame];
_position = frame.position;
decodedDuration += frame.duration;
if (decodedDuration > minDuration)
finished = YES;
}
} else {
count++;
}
if (0 == len)
break;
pktSize -= len;
}
}
av_free_packet(&packet);
}
} while (totalDuration > 0);
_reading = [NSNumber numberWithInt:0];
return result;
}
}
return result;

How to play pcm audio buffer from a socket server using audio unit circular buffer

I hope someone can help me. I am new to Objective-c and OSX and I am trying to play audio data I am receiving via socket into my audio queue. I found out this link https://stackoverflow.com/a/30318859/4274654 which in away address my issue with circular buffer.
However when I try to run my project it returns
It returns an error (OSStatus) -10865. That is why the code logs " Error enabling AudioUnit output bus".
status = AudioUnitSetProperty(_audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, kOutputBus, &one, sizeof(one));
Here is my code:
Test.h
#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "TPCircularBuffer.h"
#interface Test : Communicator
#property (nonatomic) AudioComponentInstance audioUnit;
#property (nonatomic) TPCircularBuffer circularBuffer;
-(TPCircularBuffer *) outputShouldUseCircularBuffer;
-(void) start;
#end
Test.m
#import "Test.h"
#define kOutputBus 0
#define kInputBus 1
#implementation Test{
BOOL stopped;
}
static OSStatus OutputRenderCallback(void *inRefCon,
AudioUnitRenderActionFlags *ioActionFlags,
const AudioTimeStamp *inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList *ioData){
Test *output = (__bridge Test*)inRefCon;
TPCircularBuffer *circularBuffer = [output outputShouldUseCircularBuffer];
if( !circularBuffer ){
SInt32 *left = (SInt32*)ioData->mBuffers[0].mData;
for(int i = 0; i < inNumberFrames; i++ ){
left[ i ] = 0.0f;
}
return noErr;
};
int32_t bytesToCopy = ioData->mBuffers[0].mDataByteSize;
SInt16* outputBuffer = ioData->mBuffers[0].mData;
uint32_t availableBytes;
SInt16 *sourceBuffer = TPCircularBufferTail(circularBuffer, &availableBytes);
int32_t amount = MIN(bytesToCopy,availableBytes);
memcpy(outputBuffer, sourceBuffer, amount);
TPCircularBufferConsume(circularBuffer,amount);
return noErr;
}
-(void) start
{
[self circularBuffer:&_circularBuffer withSize:24576*5];
stopped = NO;
[self setupAudioUnit];
// [super setup:#"http://localhost" port:5321];
}
-(void) setupAudioUnit
{
AudioComponentDescription desc;
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_VoiceProcessingIO;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
AudioComponent comp = AudioComponentFindNext(NULL, &desc);
OSStatus status;
status = AudioComponentInstanceNew(comp, &_audioUnit);
if(status != noErr)
{
NSLog(#"Error creating AudioUnit instance");
}
// Enable input and output on AURemoteIO
// Input is enabled on the input scope of the input element
// Output is enabled on the output scope of the output element
UInt32 one = 1;
status = AudioUnitSetProperty(_audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, kOutputBus, &one, sizeof(one));
if(status != noErr)
{
NSLog(#"Error enableling AudioUnit output bus");
}
// Explicitly set the input and output client formats
// sample rate = 44100, num channels = 1, format = 16 bit int point
AudioStreamBasicDescription audioFormat = [self getAudioDescription];
status = AudioUnitSetProperty(_audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, kOutputBus, &audioFormat, sizeof(audioFormat));
if(status != noErr)
{
NSLog(#"Error setting audio format");
}
AURenderCallbackStruct renderCallback;
renderCallback.inputProc = OutputRenderCallback;
renderCallback.inputProcRefCon = (__bridge void *)(self);
status = AudioUnitSetProperty(_audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Global, kOutputBus, &renderCallback, sizeof(renderCallback));
if(status != noErr)
{
NSLog(#"Error setting rendering callback");
}
// Initialize the AURemoteIO instance
status = AudioUnitInitialize(_audioUnit);
if(status != noErr)
{
NSLog(#"Error initializing audio unit");
}
}
- (AudioStreamBasicDescription)getAudioDescription {
AudioStreamBasicDescription audioDescription = {0};
audioDescription.mFormatID = kAudioFormatLinearPCM;
audioDescription.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked | kAudioFormatFlagsNativeEndian;
audioDescription.mChannelsPerFrame = 1;
audioDescription.mBytesPerPacket = sizeof(SInt16)*audioDescription.mChannelsPerFrame;
audioDescription.mFramesPerPacket = 1;
audioDescription.mBytesPerFrame = sizeof(SInt16)*audioDescription.mChannelsPerFrame;
audioDescription.mBitsPerChannel = 8 * sizeof(SInt16);
audioDescription.mSampleRate = 44100.0;
return audioDescription;
}
-(void)circularBuffer:(TPCircularBuffer *)circularBuffer withSize:(int)size {
TPCircularBufferInit(circularBuffer,size);
}
-(void)appendDataToCircularBuffer:(TPCircularBuffer*)circularBuffer
fromAudioBufferList:(AudioBufferList*)audioBufferList {
TPCircularBufferProduceBytes(circularBuffer,
audioBufferList->mBuffers[0].mData,
audioBufferList->mBuffers[0].mDataByteSize);
}
-(void)freeCircularBuffer:(TPCircularBuffer *)circularBuffer {
TPCircularBufferClear(circularBuffer);
TPCircularBufferCleanup(circularBuffer);
}
-(TPCircularBuffer *) outputShouldUseCircularBuffer
{
return &_circularBuffer;
}
-(void) stop
{
OSStatus status = AudioOutputUnitStop(_audioUnit);
if(status != noErr)
{
NSLog(#"Error stopping audio unit");
}
TPCircularBufferClear(&_circularBuffer);
_audioUnit = nil;
stopped = YES;
}
-(void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)event{
switch (event) {
case NSStreamEventOpenCompleted:
NSLog(#"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (stream == [super inputStream]) {
NSLog(#"NSStreamEventHasBytesAvailable");
uint8_t buffer[1024];
NSUInteger len;
while ([[super inputStream] hasBytesAvailable]) {
len = [[super inputStream] read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
//converting buffer to byte data
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
if (nil != output) {
//NSLog(#"server overideddddd said: %#", output);
}
NSData *data0 = [[NSData alloc] initWithBytes:buffer length:len];
if (nil != data0) {
SInt16* byteData = (SInt16*)malloc(len);
memcpy(byteData, [data0 bytes], len);
double sum = 0.0;
for(int i = 0; i < len/2; i++) {
sum += byteData[i] * byteData[i];
}
Byte* soundData = (Byte*)malloc(len);
memcpy(soundData, [data0 bytes], len);
if(soundData)
{
AudioBufferList *theDataBuffer = (AudioBufferList*) malloc(sizeof(AudioBufferList) *1);
theDataBuffer->mNumberBuffers = 1;
theDataBuffer->mBuffers[0].mDataByteSize = (UInt32)len;
theDataBuffer->mBuffers[0].mNumberChannels = 1;
theDataBuffer->mBuffers[0].mData = (SInt16*)soundData;
NSLog(#"soundData here");
[self appendDataToCircularBuffer:&_circularBuffer fromAudioBufferList:theDataBuffer];
}
}
}
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(#"Can't connect to server");
break;
case NSStreamEventEndEncountered:
[stream close];
[stream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
break;
default:
NSLog(#"Unknown event");
}
[super stream:stream handleEvent:event];
}
#end
I would highly appreciate if there is any one with an example of playing buffers returned from a socket server into audio queue so that I can be able to listen to sound as it comes from the socket server.
Thanks
Your code seems to be asking for a kAudioUnitSubType_VoiceProcessingIO audio unit. But kAudioUnitSubType_RemoteIO would be a more suitable iOS audio unit for just playing buffers of audio samples.
Also, your code does not seem to first select an appropriate audio session category and activate it before playing audio. See Apple's documentation for doing this: https://developer.apple.com/library/content/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/Introduction/Introduction.html

i have a issue on encryption and decryption using rc4 algorithm in ios

I am using rc4 algorithm to encrypt and decrypt a video. I am taking 64 bytes and encrypting.
as the same way I am doing the decryption also but my video is not playing.Anyone have idea about this???
- (void)encryptOnFly:(UInt8*)buffer bytesRead:(NSInteger)bytesRead
{
for(long long i=0;i<bytesRead;i++)
{
[self push:buffer[i]];
if([self isFull])
{
unsigned char *buf11=[self retrieveArray];
unsigned char buf1[64];
for(int j=0;j<64;j++)
{
buf1[j]=*buf11++;
}
NSData *data = [NSData dataWithBytes:buf1 length:sizeof(buf1)];
aesCrypt = [data RC4EncryptDecryptWithKey:#"ABCD" operation:kCCEncrypt];
// aesCrypt=[data EncryptAES:#"akey"];
const uint8_t *bytes = (const uint8_t*)[aesCrypt bytes];
for(int j=0;j<63;j++)
{
buf1[j]=*bytes++;
}
[[self fileDownloadOutputStream] write:buf1 maxLength:64];
[self empty];
}
}
}
this is the code to handle a file which is divisible by 64....
switch (type) {
case kCFStreamEventHasBytesAvailable:
[self handleBytesAvailable];
break;
case kCFStreamEventEndEncountered:
NSLog(#"REACHED :: -- > kCFStreamEventEndEncountered");
if (isEncryptionRequired)
{
if(pointer>-1)
{
remBytes=pointer+1;
int tmp=64-remBytes;
for(int k=0;k<tmp;k++)
{
if (pointer!=62)
{
if(![self isFull])
[self push:0];
}
else
if(![self isFull])
[self push:remBytes];
if ([self isFull])
{
unsigned char *buf11= [self retrieveArray];
unsigned char buf1[64];
for(int j=0;j<64;j++)
{
buf1[j]=*buf11++;
}
NSData *data = [NSData dataWithBytes:buf1 length:sizeof(buf1)];
aesCrypt = [data RC4EncryptDecryptWithKey:#"ABCD" operation:kCCEncrypt];
// aesCrypt=[data EncryptAES:#"akey"];
const uint8_t *bytes = (const uint8_t*)[aesCrypt bytes];
for(int j=0;j<63;j++)
{
buf1[j]=*bytes++;
}
[[self fileDownloadOutputStream] write:buf1 maxLength:16];
[self empty];
}}
}
else
{
unsigned char extrabuf=0;
[[self fileDownloadOutputStream] write:extrabuf maxLength:1];
///add
}
}
else
{
[[self fileDownloadOutputStream] write:buf maxLength:16];
}
[self handleStreamComplete];
break;
case kCFStreamEventErrorOccurred:
[self handleStreamError];
break;
default:
break;
}
this is the method to decrypt a file......
- (void)decryptFile:(NSString *)OMfileUrl
{
// NSLog(#"omurl::%#",OMfileUrl);
#try
{
__block NSURL *movieURL;
isOffline = YES;
{
const char *srcfile = [OMfileUrl cStringUsingEncoding:NSUTF8StringEncoding];
source = fopen(srcfile, "rb");
filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"assetforplay.mp4"];
AppDelegate *delegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
delegate.filePath = filePath;
filePathCharArr = [filePath cStringUsingEncoding:NSUTF8StringEncoding];
remove([filePath cStringUsingEncoding:NSUTF8StringEncoding]);
if (source)
{
destination = fopen(filePathCharArr, "wb");
cancelDecryption = NO;
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{
unsigned char temp[64];
long long totalBytes=0;
fseek(source, 0L, SEEK_END);
long long sz = ftell(source);
fseek(source, 0L, SEEK_SET);
int percentage=0,prevPercentage=0;
int xx=sz%64;
percentageLabel.hidden = NO;
if (xx==0)
{
NSData *data;
while (totalBytes<=(sz-64))
{
if(!cancelDecryption)
{
percentage =((double)totalBytes/(double)sz)*100;
if (percentage!=prevPercentage)
{
prevPercentage=percentage;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[percentageLabel setText:[NSString stringWithFormat:#"%i%%",percentage]];
}];
}
fread(buffer,1, 64, source);
// memcpy( buf, buffer, 16);
// memcpy( keyoffline, [delegate secretKey], 16 + 0 * 8);
// aes_set_key( &ctx, keyoffline, 128 + 0 * 64);
// aes_decrypt( &ctx, buf, buf );
data = [NSData dataWithBytes:buffer length:64];
aesCrypt = [data RC4EncryptDecryptWithKey:#"ABCD" operation:kCCDecrypt];
// aesCrypt=[data DecryptAES:#"akey"];
const uint8_t *bytes = (const uint8_t*)[aesCrypt bytes];
for(int j=0;j<63;j++)
{
buf[j]=*bytes++;
}
fwrite(buf, 1, 64, destination);
totalBytes=totalBytes+64;
}
else
{
percentageLabel.text=#"";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *err;
if (![fileManager removeItemAtPath:filePath error:&err])
{
NSLog(#"Unable to delete the essence. Reason:%#",[err description]);
}
break;
}
}
fseek(source, -64, SEEK_END);
sz = ftell(source);
// fread(buffer, 1, 16, source);
// memcpy( buf, buffer, 16);
// memcpy( keyoffline, [delegate secretKey], 16 + 0 * 8);
// aes_set_key( &ctx, keyoffline, 128 + 0 * 64);
// aes_decrypt( &ctx, buf, buf );
data = [NSData dataWithBytes:buffer length:64];
aesCrypt = [data RC4EncryptDecryptWithKey:#"ABCD" operation:kCCDecrypt];
// aesCrypt=[data DecryptAES:#"akey"];
const uint8_t *bytes = (const uint8_t*)[aesCrypt bytes];
for(int j=0;j<63;j++)
{
buf[j]=*bytes++;
}
int buf1 = buf[63];
for(int j=0;j<buf1;j++)
{
temp[j] = buf[j];
}
fwrite(temp, 1, buf1, destination);
}
else
{
NSData *data;
while (totalBytes<=(sz-1))
{
if(!cancelDecryption)
{
percentage =((double)totalBytes/(double)sz)*100;
if (percentage!=prevPercentage)
{
prevPercentage=percentage;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[percentageLabel setText:[NSString stringWithFormat:#"%i%%",percentage]];
}];
}
fread(buffer,1, 64, source);
// memcpy( buf, buffer, 16);
// memcpy( keyoffline, [delegate secretKey], 16 + 0 * 8);
// aes_set_key( &ctx, keyoffline, 128 + 0 * 64);
// aes_decrypt( &ctx, buf, buf );
data = [NSData dataWithBytes:buffer length:64];
aesCrypt = [data RC4EncryptDecryptWithKey:#"ABCD" operation:kCCDecrypt];
// aesCrypt=[data DecryptAES:#"akey"];
const uint8_t *bytes = (const uint8_t*)[aesCrypt bytes];
for(int j=0;j<63;j++)
{
buf[j]=*bytes++;
}
fwrite(buf, 1, 64, destination);
totalBytes=totalBytes+64;
}
else
{
percentageLabel.text=#"";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *err;
if (![fileManager removeItemAtPath:filePath error:&err])
{
NSLog(#"Unable to delete the essence. Reason:%#",[err description]);
}
break;
}
}
}
dispatch_async(dispatch_get_main_queue(), ^{
percentageLabel.text=#"";
if (!cancelDecryption)
{
percentageLabel.hidden = YES;
movieURL = [NSURL fileURLWithPath:filePath];
[self.mediaPanelViewCtrl setURL:movieURL];
}
});
});
}
}
}
#catch (NSException *exception)
{
NSLog(#"Exception in decrypt file::%#",[exception description]);
}
}
this is the method to do encryption and decryption using RC4....
- (NSData*)RC4EncryptDecryptWithKey:(NSString *)key operation:(CCOperation)operation
{
// convert to C string..
int keySize = [key length];
char keyPtr[keySize];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr
maxLength:sizeof(keyPtr)
encoding:NSUTF8StringEncoding];
// encode/decode
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength;
void *buffer = malloc(bufferSize);
size_t numBytesOut = 0;
CCCryptorStatus cryptStatus = CCCrypt(operation,
kCCAlgorithmRC4,
kCCOptionECBMode,
keyPtr,
kCCKeySizeMinRC4,
NULL,
[self bytes],
dataLength,
buffer,
bufferSize,
&numBytesOut);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer
length:numBytesOut
freeWhenDone:YES];
}
free(buffer);
return nil;
}

How to Use BOOL in IBACTION IOS

i need to connect an imap email server with below given -(BOOL) method
how can i call this method in IBACTION when connect button clicked?
- (BOOL) connectToHost: (NSString*) hostname
{
socket_ = socket(AF_INET, SOCK_STREAM, 0);
if (socket_ < 0) {
NSLog(#"socket");
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(993);
struct hostent* host = gethostbyname([hostname UTF8String]);
unsigned int** ptr = (unsigned int **) host->h_addr_list;
while (*ptr != NULL) {
addr.sin_addr.s_addr = *(*ptr);
if (connect(socket_, (struct sockaddr *) &addr, sizeof(addr)) == 0) {
break;
}
ptr++;
}
if (*ptr == NULL) {
NSLog(#"connect");
}
return [[self readLine] isEqualToString: #"* OK"];
}
... call it from another method?
- (IBAction) connectButtonClicked:(id)sender {
[self connectToHost:#"Your host name goes here, variable _or_ constant! :D"];
}