Block calls and sms in Iphone iOS while application running - iphone

while using app I want to block all incoming calls and sms. How can I do this? I know example link http://tech.ruimaninfo.com/?p=83. But there are errors in code.It should work at least on jailbroken iphone.

Below is some code that I've adapted from that website, and works for me on my non jailbroken device:
Firstly add "CoreTelephony.framework" to your project then import it into your view controller like so:
#import <CoreTelephony/CoreTelephonyDefines.h>
Next, add the following code:
extern NSString const *kCTSMSMessageReceivedNotification;
extern NSString const *kCTSMSMessageReplaceReceivedNotification;
extern NSString const *kCTSIMSupportSIMStatusNotInserted;
extern NSString const *kCTSIMSupportSIMStatusReady;
typedef struct __CTCall CTCall;
extern NSString *CTCallCopyAddress(void*, CTCall *);
void * CTSMSMessageSend(id server,id msg);
typedef struct __CTSMSMessage CTSMSMessage;
NSString *CTSMSMessageCopyAddress(void *, CTSMSMessage *);
NSString *CTSMSMessageCopyText(void *, CTSMSMessage *);
int CTSMSMessageGetRecordIdentifier(void * msg);
NSString * CTSIMSupportGetSIMStatus();
NSString * CTSIMSupportCopyMobileSubscriberIdentity();
id CTSMSMessageCreate(void* unknow/*always 0*/,NSString* number,NSString* text);
void * CTSMSMessageCreateReply(void* unknow/*always 0*/,void * forwardTo,NSString *text);
id CTTelephonyCenterGetDefault(void);
void CTTelephonyCenterAddObserver(id, id, CFNotificationCallback, NSString *, void *,int);
void CTTelephonyCenterRemoveObserver(id,id,NSString*,void*);
int CTSMSMessageGetUnreadCount(void);
void * CTCallDisconnect(CTCall *call);
static void callback(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
NSString *notifyname = (__bridge NSString *)name;
if ([notifyname isEqualToString:#"kCTCallIdentificationChangeNotification"]) {
NSDictionary *info = (__bridge NSDictionary *)userInfo;
CTCall *call = (__bridge CTCall *)[info objectForKey:#"kCTCall"];
NSString *caller = CTCallCopyAddress(NULL, call);
NSLog(#"RECEIVED CALL: %#", caller);
CTCallDisconnect(call);
}
}
static void signalHandler(int sigraised) {
printf("\nInterrupted.\n");
exit(0);
}
And in viewDidLoad or some other appropriate method, add the following:
id ct = CTTelephonyCenterGetDefault();
CTTelephonyCenterAddObserver(ct, NULL, callback, NULL, NULL, CFNotificationSuspensionBehaviorHold);
sig_t oldHandler = signal(SIGINT, signalHandler);
if (oldHandler == SIG_ERR) {
printf("Could not establish new signal handler");
exit(1);
}
printf("Starting run loop and watching for notification.\n");
CFRunLoopRun();
For now this code is merely a proof of concept and would have to be expanded upon for error handling and whatnot, but you should get the idea.

Related

Block sms in Iphone iOS

While using app I want to block all incoming calls and SMS. It should work at least on jailbroken iphone. I have this code that block calls, but not SMS - how can I fix that?
importCoreTelephony/CoreTelephonyDefines.h>
extern NSString const *kCTSMSMessageReceivedNotification; extern
NSString const *kCTSMSMessageReplaceReceivedNotification; extern
NSString const *kCTSIMSupportSIMStatusNotInserted; extern NSString
const *kCTSIMSupportSIMStatusReady;
typedef struct __CTCall CTCall; extern NSString
CTCallCopyAddress(void, CTCall *);
void * CTSMSMessageSend(id server,id msg); typedef struct
__CTSMSMessage CTSMSMessage; NSString *CTSMSMessageCopyAddress(void *, CTSMSMessage *); NSString *CTSMSMessageCopyText(void *, CTSMSMessage
*);
int CTSMSMessageGetRecordIdentifier(void * msg); NSString *
CTSIMSupportGetSIMStatus(); NSString *
CTSIMSupportCopyMobileSubscriberIdentity();
id CTSMSMessageCreate(void* unknow/always 0/,NSString*
number,NSString* text); void * CTSMSMessageCreateReply(void*
unknow/always 0/,void * forwardTo,NSString *text);
id CTTelephonyCenterGetDefault(void); void
CTTelephonyCenterAddObserver(id, id, CFNotificationCallback, NSString
*, void ,int); void CTTelephonyCenterRemoveObserver(id,id,NSString,void*); int
CTSMSMessageGetUnreadCount(void);
void * CTCallDisconnect(CTCall *call);
static void callback(CFNotificationCenterRef center, void *observer,
CFStringRef name, const void *object, CFDictionaryRef userInfo) {
NSString *notifyname = (__bridge NSString *)name;
if ([notifyname
isEqualToString:#"kCTCallIdentificationChangeNotification"]) {
NSDictionary *info = (__bridge NSDictionary *)userInfo;
CTCall *call = (__bridge CTCall *)[info objectForKey:#"kCTCall"];
NSString *caller = CTCallCopyAddress(NULL, call);
NSLog(#"RECEIVED CALL: %#", caller);
CTCallDisconnect(call);
} }
static void signalHandler(int sigraised) {
printf("\nInterrupted.\n"); exit(0); }
In viewdidload:
id ct = CTTelephonyCenterGetDefault();
CTTelephonyCenterAddObserver(ct, NULL, callback, NULL, NULL,
CFNotificationSuspensionBehaviorHold);
sig_t oldHandler = signal(SIGINT, signalHandler); if (oldHandler ==
SIG_ERR) {
printf("Could not establish new signal handler"); exit(1); }
printf("Starting run loop and watching for notification.\n");
CFRunLoopRun();
i think you have made some syntatical error in following line ,check it
id CTSMSMessageCreate(void* unknow/*always 0*/,NSString* number,NSString* text);
void * CTSMSMessageCreateReply(void* unknow/*always 0*/,void * forwardTo,NSString *text);

NSString * to Char[] (GameCenter Send Struct)

I want to send a struct to another player in GameCenter.
I have read the other questions about this, however, I cannot get any of them to work.
I need to get #"1234" into a char[4] (ex char[0] = '1', char[1] = '2', etc)
I have tried [NSString UTF8String], but it doesn't seem to do what I want.
It assigns fine, but when I pull it back into NSString * with [NSString stringWithUTF8String:], It returns blank.
If someone could show me the conversion to and from, it would be greatly appreciated.
Thanks.
EDIT:
I can't get it to work :/ Here is my code (the abridged version):
Matchmaker.h
enum { NChars = 4 };
typedef struct {
MessageType messageType;
} Message;
typedef struct {
Message message;
char code[NChars];
} MessageGameCode;
#interface Matchmaker : CCLayer <GameCenterMasterDelegate>{
NSString *_code;
}
#property (nonatomic,retain) NSString *_code;
Matchmaker.m
#synthesize _code;
-(void)viewDidLoad{
self._code = #"1234";
}
- (void)sendCode {
NSLog(#"Sending Code....");
MessageGameCode message;
message.message.messageType = kMessageTypeGameCode;
NSString * const source = self._code;
const char* const sourceAsUTF8 = source.UTF8String;
for (size_t idx = 0; idx < NChars; ++idx) {
message.code[idx] = sourceAsUTF8[idx];
}
NSData *data = [NSData dataWithBytes:&message length:NChars];
[self sendData:data];
}
- (void)match:(GKMatch *)match didReceiveData:(NSData *)data fromPlayer:(NSString *)playerID {
Message *message = (Message *) [data bytes];
if (message->messageType == kMessageTypeGameCode) {
MessageGameCode *codeMessage = (MessageGameCode *)[data bytes];
self._code = [[NSString alloc] initWithBytes:codeMessage->code length:NChars encoding:NSUTF8StringEncoding];
[self setGameState:kGameStateWaitingForStart];
NSLog(#"Game Code Recieved");
NSLog(#"Recieved Code: %#",self._code); //This always shows self._code as blank
}
}
Your attempt will fail because the cstring which you pass to + [NSString stringWithUTF8String:] is not terminated.
Try this:
NSString * result = [[NSString alloc] initWithBytes:bytes
length:4
encoding:NSUTF8StringEncoding];
Edit
A more complete demonstration:
enum { NChars = 4 };
/* requires error checking */
void transmit() {
NSString * const source = #"1234";
char tmp[NChars] = { 0 };
const char* const sourceAsUTF8 = source.UTF8String;
for (size_t idx = 0; idx < NChars; ++idx) {
tmp[idx] = sourceAsUTF8[idx];
}
/* .. */
}
/* requires error checking */
void receive(const char bytes[NChars]) {
NSString * result = [[NSString alloc] initWithBytes:bytes length:NChars encoding:NSUTF8StringEncoding];
/* ... */
}
One way is
char bytes[4];
NSData* data = [#"1234" dataUsingEncoding: NSUTF8StringEncoding];
if ([data length] <= 4)
{
memcpy(bytes, [data bytes], [data length]);
}
And to go the other way:
NSString* recodedString = [[NSString alloc] initWithBytes: bytes
length: savedLengthFromBefore
encoding: NSUTF8StringEncoding];
There are a couple of possible pitfalls here.
One is that with [NSString UTF8String] "The returned C string is automatically freed just as a returned object would be released; you should copy the C string if it needs to store it outside of the autorelease context in which the C string is created.". So, depending on how long you're expecting the value to stick around you may need to copy it (for example, using strcpy)
The other issue is that [NSString UTF8String] and [NSString stringWithUTF8String:] both expect NULL-terminated C strings, so you need a char[5], not a char[4] to hold #"1234".

Getting audio route gives empty string

I'm currently working with a piece of code to detect whether a user has plugged in/unplugged headphones with their iPhone. The method I'm using to detect it is shown below.
void audioRouteChangeListenerCallback (void *inUserData, AudioSessionPropertyID inPropertyID,UInt32 inPropertyValueSize, const void *inPropertyValue){
if (inPropertyID != kAudioSessionProperty_AudioRouteChange) return;
CFStringRef route; UInt32 routeSize = sizeof(CFStringRef);
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute,&routeSize, &route);
NSString *oldroute = (NSString*)route;
NSLog(#"Audio Route changed to: %#",oldroute);
}
My issue occurs when I go to unplug the headphones. Plugging them in works as I expect, with the Log file showing "Audio Route changed to: Headphones", however, when I unplug I get an empty string for oldroute. I was hoping that this value would be "Speaker" as it says in the Apple documents. Has anyone seen this before? Am I doing something wrong in getting the string oldroute? Thanks
I still have not found a good answer for the exact issue that I have posted as the question. Here is a workaround that may work for some people with a similar problem. This solution gives you the route that was active before the change. Ex. if you unplug your headphones you will get a string that is "Headphones" or if you put in your headphones you'll get a string that is "Speaker".
void audioRouteChangeListenerCallback (void *inUserData, AudioSessionPropertyID inPropertyID,UInt32 inPropertyValueSize, const void *inPropertyValue){
if (inPropertyID != kAudioSessionProperty_AudioRouteChange) return;
CFDictionaryRef routeChangeDictionary = (CFDictionaryRef)inPropertyValue;
CFStringRef oroute;
oroute = (CFStringRef)CFDictionaryGetValue(routeChangeDictionary, CFSTR(kAudioSession_AudioRouteChangeKey_OldRoute));
NSString *oldroute = (NSString*)oroute;
}
Hope this helps.
Edit: I'm going to accept my answer until a better one comes along
I currently use the following:
void _propertyListener( void * inClientData,
AudioSessionPropertyID inID,
UInt32 inDataSize,
const void * inData) {
if (inID != kAudioSessionProperty_AudioRouteChange) {
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:kAudioRouteChanged object:nil];
});
}
- (void) _audioRouteChanged:(NSNotification*)notification
{
NSLog(#"audioRouteChanged");
UInt32 routeSize = sizeof (CFStringRef);
CFStringRef route;
OSStatus error = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &routeSize, &route);
/* Known values of route:
* "Headset"
* "Headphone"
* "Speaker"
* "SpeakerAndMicrophone"
* "HeadphonesAndMicrophone"
* "HeadsetInOut"
* "ReceiverAndMicrophone"
* "Lineout"
*/
if (!error && (route != NULL)) {
NSString* routeStr = (__bridge NSString*)route;
NSRange headphoneRange = [routeStr rangeOfString : #"Head"];
[self.cardSwipeDelegate headphoneListener:(headphoneRange.location != NSNotFound)];
if (headphoneRange.location != NSNotFound) {
[self startSession];
} else {
[self stopSession];
}
}
}
And where ever you do your initialization add the notification:
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:#selector(_audioRouteChanged:) name:kAudioRouteChanged object:nil];

Find IP address in iphone

I want to find IP address in an application. I am able to find it. But, problem is, it works fins in iphone os 2.0 or so. But, in iphone os 3.0 it is giving me a warning:
warning: no '+currentHost' method found
warning: (Messages without a matching method signature)
I am using this code, and it works fine with os version 2.0.
-(NSString*)getAddress {
char iphone_ip[255];
strcpy(iphone_ip,"127.0.0.1"); // if everything fails
NSHost* myhost = [NSHost currentHost];
if (myhost)
{
NSString *ad = [myhost address];
if (ad)
strcpy(iphone_ip,[ad cStringUsingEncoding: NSISOLatin1StringEncoding]);
}
return [NSString stringWithFormat:#"%s",iphone_ip];
}
How to find IP address in iphone os 3.0 or greater os version?
Thanks in advance.
#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#include <ifaddrs.h>
// retun the host name
+ (NSString *)hostname
{
char baseHostName[256];
int success = gethostname(baseHostName, 255);
if (success != 0) return nil;
baseHostName[255] = '\0';
#if !TARGET_IPHONE_SIMULATOR
return [NSString stringWithFormat:#"%s.local", baseHostName];
#else
return [NSString stringWithFormat:#"%s", baseHostName];
#endif
}
// return IP Address
+ (NSString *)localIPAddress
{
struct hostent *host = gethostbyname([[self hostname] UTF8String]);
if (!host) {herror("resolv"); return nil;}
struct in_addr **list = (struct in_addr **)host->h_addr_list;
return [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding];
}
As far as I know there is only one hacky way to do that. You basically open a socket and get its address using POSIX functions. Here is the code I used for this:
http://iphonesdksnippets.com/post/2009/09/07/Get-IP-address-of-iPhone.aspx
[NSHost currentHost] will also work, but it is deprecated and considered a "Private API" by Apple, so you won't be able to submit your application to App Store.
Put this script on a web server running PHP:
<?php
$ip = getenv("REMOTE_ADDR");
echo $ip;
?>
Call this on the device:
NSURL *scriptURL = [[NSURL alloc] initWithString:#"http://yourserver.com/script.php"];
NSString *ip = [NSString stringWithContentsOfURL: scriptURL encoding:NSASCIIStringEncoding error:nil];
- (NSString *)getIPAddress {
NSString *address = #"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0) {
// Loop through linked list of interfaces
temp_addr = interfaces;
while(temp_addr != NULL) {
if(temp_addr->ifa_addr->sa_family == AF_INET) {
// Check if interface is en0 which is the wifi connection on the iPhone
// it may also be en1 on your ipad3.
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:#"en0"]) {
// Get NSString from C String
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return address;
}
Use this to get your IP
If any errors
Please use
#include <ifaddrs.h>
#include <arpa/inet.h>
Getting the IP address is a bit hacky. Are you sure you couldn't live with the device ID (UDID) that is unique to each iPhone and can be retrieved easily via the public API ?
[UIDevice currentDevice].uniqueIdentifier
There is one more way to get the IP address and that too Global IP
NSString* ip=#"http://www.whatismyip.org/";
NSURL *url = [[NSURL alloc] initWithString:ip];
NSString *ans = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
NSLog(#"%#",ans);
The above site will give you the Global IP.
Just put this in your code and use the IP address where ever you want and also get the location of the user using your app as this gives global IP.
You should have a look to this good project:
uidevice-extension
Specialy this class
Import UIDevice-Reachability.h in your project then try with one of those commands:
NSString *myIp = [UIDevice localIPAddress];
NSString *myIp = [UIDevice localWiFiIPAddress];
NSString *myIp = [UIDevice whatismyipdotcom]; // is using #aamritrao solution
bool success;
struct ifaddrs *addrs;
const struct ifaddrs *cursor;
const struct sockaddr_dl *dlAddr;
const uint8_t *base;
int i;
success = getifaddrs(&addrs) == 0;
if (success) {
cursor = addrs;
while (cursor != NULL) {
if ( (cursor->ifa_addr->sa_family == AF_LINK)
&& (((const struct sockaddr_dl *) cursor->ifa_addr)->sdl_type ==IFT_ETHER)
) {
dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
// fprintf(stderr, " sdl_nlen = %d\n", dlAddr->sdl_nlen);
// fprintf(stderr, " sdl_alen = %d\n", dlAddr->sdl_alen);
base = (const uint8_t *) &dlAddr->sdl_data[dlAddr->sdl_nlen];
printf(" MAC address ");
for (i = 0; i < dlAddr->sdl_alen; i++) {
if (i != 0) {
printf(":");
}
printf("%02x", base[i]);
}
printf("\n");
}
cursor = cursor->ifa_next;
}
}

objc_setAssociatedObject unavailable in iPhone simulator

In the 3.1 SDk, Apple added support for associated objects.
However, the simulator will not compile code that includes references to objc_setAssociatedObject, objc_getAssociatedObject, et al. (Undeclared errors)
Is there away around this? Can I make the iPhone simulator compile this code? I would hate to have to do all testing on the device.
Update
Bug Filed:
rdar://7477326
I don't think this will be fixed in the 3.x SDKs, so another fix is to just define the functions and call through to the next definition via a dynamic lookup.
Header:
#if TARGET_IPHONE_SIMULATOR
enum {
OBJC_ASSOCIATION_ASSIGN = 0,
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
OBJC_ASSOCIATION_RETAIN = 01401,
OBJC_ASSOCIATION_COPY = 01403
};
typedef uintptr_t objc_AssociationPolicy;
void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy);
id objc_getAssociatedObject(id object, void *key);
void objc_removeAssociatedObjects(id object);
#endif
Implementation:
#if TARGET_IPHONE_SIMULATOR
void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy) {
((void (*)(id, void *, id, objc_AssociationPolicy))
dlsym(RTLD_NEXT, "objc_setAssociatedObject")) (object, key, value, policy);
}
id objc_getAssociatedObject(id object, void *key) {
return ((id (*)(id, void *))
dlsym(RTLD_NEXT, "objc_getAssociatedObject"))(object, key);
}
void objc_removeAssociatedObjects(id object) {
((void (*)(id))
dlsym(RTLD_NEXT, "objc_removeAssociatedObjects"))(object);
}
#endif
A quick and dirty workaround (largely untested, may be buggy):
#if TARGET_IPHONE_SIMULATOR
#import <objc/runtime.h>
enum {
OBJC_ASSOCIATION_ASSIGN = 0,
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
OBJC_ASSOCIATION_RETAIN = 01401,
OBJC_ASSOCIATION_COPY = 01403
};
typedef uintptr_t objc_AssociationPolicy;
#implementation NSObject (OTAssociatedObjectsSimulator)
static CFMutableDictionaryRef theDictionaries = nil;
static void Swizzle(Class c, SEL orig, SEL new) // swizzling by Mike Ash
{
Method origMethod = class_getInstanceMethod(c, orig);
Method newMethod = class_getInstanceMethod(c, new);
if (class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
else
method_exchangeImplementations(origMethod, newMethod);
}
- (NSMutableDictionary *)otAssociatedObjectsDictionary
{
if (!theDictionaries)
{
theDictionaries = CFDictionaryCreateMutable(NULL, 0, NULL, &kCFTypeDictionaryValueCallBacks);
Swizzle([NSObject class], #selector(dealloc), #selector(otAssociatedObjectSimulatorDealloc));
}
NSMutableDictionary *dictionary = (id)CFDictionaryGetValue(theDictionaries, self);
if (!dictionary)
{
dictionary = [NSMutableDictionary dictionary];
CFDictionaryAddValue(theDictionaries, self, dictionary);
}
return dictionary;
}
- (void)otAssociatedObjectSimulatorDealloc
{
CFDictionaryRemoveValue(theDictionaries, self);
[self otAssociatedObjectSimulatorDealloc];
}
#end
void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)
{
NSCAssert(policy == OBJC_ASSOCIATION_RETAIN_NONATOMIC, #"Only OBJC_ASSOCIATION_RETAIN_NONATOMIC supported");
[[object otAssociatedObjectsDictionary] setObject:value forKey:[NSValue valueWithPointer:key]];
}
id objc_getAssociatedObject(id object, void *key)
{
return [[object otAssociatedObjectsDictionary] objectForKey:[NSValue valueWithPointer:key]];
}
void objc_removeAssociatedObjects(id object)
{
[[object otAssociatedObjectsDictionary] removeAllObjects];
}
#endif