I am working on a iOS application and in this application I have send SMS internally without user involvement. And After googling I found a answer and I am using this code.
xpc_connection_t myconnection;
dispatch_queue_t queue = dispatch_queue_create("com.apple.chatkit.clientcomposeserver.xpc", DISPATCH_QUEUE_CONCURRENT);
myconnection = xpc_connection_create_mach_service("com.apple.chatkit.clientcomposeserver.xpc", queue, XPC_CONNECTION_MACH_SERVICE_PRIVILEGED);
Now we have the XPC connection myconnection to the service of SMS sending. However, XPC configuration provides for creation of suspended connections —we need to take one more step for the activation.
xpc_connection_set_event_handler(myconnection, ^(xpc_object_t event){
xpc_type_t xtype = xpc_get_type(event);
if(XPC_TYPE_ERROR == xtype)
{
NSLog(#"XPC sandbox connection error: %s\n", xpc_dictionary_get_string(event, XPC_ERROR_KEY_DESCRIPTION));
}
// Always set an event handler. More on this later.
NSLog(#"Received an message event!");
});
xpc_connection_resume(myconnection);
The connection is activated. Right at this moment iOS 6 will display a message in the telephone log that this type of communication is forbidden. Now we need to generate a dictionary similar to xpc_dictionary with the data required for the message sending.
NSArray *receipements = [NSArray arrayWithObjects:#"+7 (90*) 000-00-00", nil];
NSData *ser_rec = [NSPropertyListSerialization dataWithPropertyList:receipements format:200 options:0 error:NULL];
xpc_object_t mydict = xpc_dictionary_create(0, 0, 0);
xpc_dictionary_set_int64(mydict, "message-type", 0);
xpc_dictionary_set_data(mydict, "recipients", [ser_rec bytes], [ser_rec length]);
xpc_dictionary_set_string(mydict, "text", "hello from your application!");
Little is left: send the message to the XPC port and make sure it is delivered.
xpc_connection_send_message(myconnection, mydict);
xpc_connection_send_barrier(myconnection, ^{
NSLog(#"Message has been successfully delievered");
});
But for using this code I have to add xpc.h header file, but xpc.h header is not found. So, suggest what actually I need to do.
You're using XPC in iOS, and the headers aren't going to be there for you by default. I got the /usr/include from https://github.com/realthunder/mac-headers -- it includes the xpc.h and related headers. I took the /xpc subdirectory from that and added only it to my project, because adding the full /usr/include interfered with my existing /usr/include and caused an architecture error on compile.
Even after adding the /xpc subdirectory and including xpc.h, I was unable to get the include paths to work due to nested include problems. Wasted lots of time trying to get the proper solution, then used the kludgy solution of editing xpc.h and base.h so that the nested xpc includes didn't use any path. So, #include <xpc/base.h> was edited to #include "base.h", etc.
That worked, the app builds and runs after that.
the library path its wrong use this ...
#include /usr/include/xpc/xpc.h
Related
I'm displaying RTSP streams from IP cameras. I want to replace this method avcodec_decode_video2 with VideoToolbox framework. I'm kinda new with video data processing so I'm a little lost...
I've tested both solutions from here and here, but I end up with a failure for this method VTDecompressionSessionDecodeFrame.
Error Domain=NSOSStatusErrorDomain Code=-12909 "The operation couldn’t be completed. (OSStatus error -12909.)" - -12909
I suspect this is coming from the session because if I call this VTDecompressionSessionCanAcceptFormatDescription right after creating the session, the result is NO.
Here is how is created my session :
VTDecompressionOutputCallbackRecord callback;
callback.decompressionOutputCallback = decompressionSessionDecodeFrameCallback;
callback.decompressionOutputRefCon = (__bridge void *)self;
NSDictionary *destinationImageBufferAttributes =[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],(id)kCVPixelBufferOpenGLESCompatibilityKey,[NSNumber numberWithInt:kCVPixelFormatType_32RGBA],(id)kCVPixelBufferPixelFormatTypeKey,nil];
OSStatus status = VTDecompressionSessionCreate(kCFAllocatorDefault, _formatDesc, NULL,
(__bridge CFDictionaryRef)destinationImageBufferAttributes,
&callback, &_decompressionSession);
I'm also not sure about the data to use. I have a choice between AVPacket.data, AVCodecContext.extradata, AVPacket.buf->data. Can anyone tell me which one should I use (maybe there is another one) ?
Thx in advance,
PS.: This is my first post ; let me know if it is not correctly presented/explained.
I've succeeded to get one successful status for this method. Turns out that I had indexes issues and the code I pasted had some bugs (at least, it wasn't adapted for my situation, specially for managing NALU types 1 and 5).
I have another issues because all the other calls returns a failure but I think I must post another question.
I'm Using two native iOS Apps to implement Good Dynamic Framework app kinetics, for now I'm successfully able to send a consumer request, received it at producer end and send a reply form producer , received at consumer end. using
sendTo (GDServiceClient) >>>>>>>>>>>>>>> GDServiceDidReceiveFrom
GDServiceClientDidReceiveFrom <<<<<<<<<<< replyTo (GDService).
problem arise when I try to send a pdf file from producer to consumer and read it at the consumer end.
I use the "GDServiceClient sendTo" method to send the file as its attachment. seems like file received by the consumer end successfully. I can see the good
console Xcode log
GTICCConnection: Number of attachments: 1
GTICCConnection: Finished reading data from all attachments 1/1. Last file size: 273459
I received the file path from attachment as "Inbox/BundleID/....../myfile.pdf"
But the Problem is GDFileManger contentsAtPath:fileInboxPath become nil and cannot read the file.
Questions
1.Can any one help me to resolve this issue. Is there a special way to read the file from GD Inbox?
Why GDFileManager always need a valid NSFilePath when create a new file using createFileAtPath: ? it says it encrypt the file and file won't be at the physical path.
I found it. I will reply with a detailed answer in few days. until that,
Before read the file content I use check for file existence like this.
if ([[GDFileManager defaultManager] fileExistsAtPath:fileInboxPath]){
NSData *fileData = [[GDFileManager defaultManager] contentsAtPath:fileInboxPath];
NSLog(#"Filedata: %#",fileData);
NSString *content = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
}
but This if condition fails. After I commented out the line
[[GDFileManager defaultManager] fileExistsAtPath:fileInboxPath]
it starts working.
I'm trying to use OpenAL for an IOS game I'm working on, but having an issue opening the audio device. Specifically, when I call the function alcOpenDevice(NULL), I get 'NULL' in return. This is causing issues, of course, but I can't tell what I'm doing wrong.
I'm new to OpenAL, so I've been looking at a couple guides here and here to see what I need to do. If I download their sample projects and test 'em, they both work fine. If I copy their files into my project, and ignore the files I made, they still work fine. I'm assuming something got lost in translation when I started rebuilding the code for use in my project. Asking around and searching online hasn't given me any leads though, so I'm hoping someone here could put me on the right track.
Here's the actual setup code I'm using in my AudioPlayer.m
- (void)setup {
audioSampleBuffers = [NSMutableDictionary new];
audioSampleSources = [NSMutableArray new];
[self setupAudioSession];
[self setupAudioDevice];
[self setupNotifications];
}
- (BOOL)setupAudioSession {
// // This has been depricated.
//
// /* Setup the Audio Session and monitor interruptions */
// AudioSessionInitialize(NULL, NULL, AudioInterruptionListenerCallback, NULL);
//
// /* Set the category for the Audio Session */
// UInt32 session_category = kAudioSessionCategory_MediaPlayback;
// AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(session_category), &session_category);
//
// /* Make the Audio Session active */
// AudioSessionSetActive(true);
BOOL success = NO;
NSError *error = nil;
AVAudioSession *session = [AVAudioSession sharedInstance];
success = [session setCategory:AVAudioSessionCategoryPlayback error:&error];
if (!success) {
NSLog(#"%# Error setting category: %#", NSStringFromSelector(_cmd), [error localizedDescription]);
return success;
}
success = [session setActive:YES error:&error];
if (!success) {
NSLog(#"Error activating session: %#", [error localizedDescription]);
}
return success;
}
- (BOOL)setupAudioDevice {
// 'NULL' uses the default device.
openALDevice = alcOpenDevice(NULL); // Returns 'NULL'
ALenum error = alGetError(); // Returns '0'
NSLog(#"%i", error);
if (!openALDevice) {
NSLog(#"Something went wrong setting up the audio device.");
return NO;
}
// Create a context to use with the device, and make it the current context.
openALContext = alcCreateContext(openALDevice, NULL);
alcMakeContextCurrent(openALContext);
[self createAudioSources];
// Setup was successful
return YES;
}
- (void)createAudioSources {
ALuint sourceID;
for (int i = 0; i < kMaxConcurrentSources; i++) {
// Create a single source.
alGenSources(1, &sourceID);
// Add it to the array.
[audioSampleSources addObject:[NSNumber numberWithUnsignedInt:sourceID]];
}
}
Note: I'm running IOS 7.1.1 on a new iPad air, and using Xcode 5.1.1. This issue has been confirmed on the iPad, my simulator, and an iPod touch.
The Short Answer:
Apple's implementation of alcOpenDevice() only returns the device once. Every subsequent call returns NULL. This function can be called by a lot of Apple audio code, so take out EVERY TRACE of audio code before using OpenAL and manually calling that function yourself.
The Long Answer:
I spent half a day dealing with this problem while using ObjectAL, and ended up doing exactly what you did, re-making the entire project. It worked, until out of curiosity I copied the entire project over, then same problem again, alcOpenDevice(NULL) returned NULL. By chance I stumbled upon the answer. It was this bit of code in my swift game scene:
let jumpSound = SKAction.playSoundFileNamed("WhistleJump.mp3", waitForCompletion: false)
And then I remembered I had this problem before without SKAction involved. That time it turned out I was using ObjectAL in two different ways, I used OALSimpleAudio in one place, and OpenAL objects in another, and it was initializing my audio session twice.
The common thread between these two incidents is both times alcOpenDevice() was called more than once during the life of the application. The first time it was ObjectAL calling it twice due to my misuse of the library. The second SKAction.playSoundFileNamed() must have called alcOpenDevice() before my ObjectAL code did. Upon further research I found this bit in the OpenAL 1.1 Specification:
6.1.1. Connecting to a Device
The alcOpenDevice function allows the application (i.e. the client program) to connect to a device (i.e. the server).
ALCdevice * alcOpenDevice (const ALCchar *deviceSpecifier);
If the function returns NULL, then no sound driver/device has been found. The argument is a null terminated string that requests a certain device or device configuration. If NULL is specified, the implementation will provide an implementation specific default.
My hunch is that Apple's implementation of this function only returns the correct device ONCE for the life of the application. Every time alcOpenDevice is called after that, it returns NULL. So bottom line: Take out every trace of audio code before switching to OpenAL. Even code that seems safe, like SKAction.playSoundFileNamed() still might contain a call to alcOpenDevice() buried deep in its implementation.
For those using ObjectAL, here is the console output of this problem to help them find their way here from google, as I couldn't find a good answer myself:
OAL Error: +[ALWrapper openDevice:]: Could not open device (null)
OAL Error: -[ALDevice initWithDeviceSpecifier:]: <ALDevice: 0x17679b20>: Failed to create OpenAL device (null)
OAL Error: +[ALWrapper closeDevice:]: Invalid Enum (error code 0x0000a003)
OAL Warning: -[OALAudioSession onAudioError:]: Received audio error notification, but last reset was 0.012216 seconds ago. Doing nothing.
fatal error: unexpectedly found nil while unwrapping an Optional value
This SO answer seems to validate my comment about AVAudioSession conflicting with OpenAL. Try removing AVAudioSession, or initializing OpenAL first (tho I imagine this would cause the inverse problem).
Alright, so I ended up starting over in a fresh project with a copy-pasted version of AudioSamplePlayer from the first sample project I linked. -It worked.
I then edited it step by step back to the format I had set up in my project. -It still works!
I still don't know what I did wrong the first time, and I'm not sure it was even in my audio player anymore, but It's running now. I blame gremlins.
...maybe alien surveillance.
I am using compiled version of rtmp-dump from github in my iOS project. Following is the code to connect to the server.
rtmp = RTMP_Alloc();
RTMP_Init(rtmp);
NSString *url = #"rtmp://192.168.0.119:1935/red5/sw231/";
char *strUrl = (char *)[url cStringUsingEncoding:NSASCIIStringEncoding];
RTMP_SetupURL(rtmp, strUrl);
RTMP_Connect(rtmp, NULL);
Since the proper documentation of rtmp-dump OR lib-rtmp is not available I want to know the methods that I can use for the following functionalities.
I want to send an array of values while connecting. My query is by what method of rtmp-dump can I send values to the server when connecting?
How can I call certain methods of the server and pass parameters to the server?
How can I receive response from the server? As well as how can I implement client-side method invocation through rtmp-dump?
How can I explicitly provide the name of the stream which I want to play or listen to after connecting?
By using RTMP_Close(), will I be able to disconnect the connection?
I know this post was asked 12 months ago but this may be usefull.
Download this and see the examples of usage of librtmp. I don't know why this library has no documentation but following that examples can help you a bit.
I am making an iOS client for the Stack Exchange API. After a long, drawn out fight I finally managed to implement authentication - which gives me a token I stick into a URL. When the token is valid, the URL looks like this:
https://api.stackexchange.com/2.1/me/associated?key=_____MY_SECRET_KEY______&access_token=_____ACCESS_TOKEN_:)_____
which, when valid, brings me to this JSON in a webpage:
{"items":[{"site_name":"Stack Overflow","site_url":"http://stackoverflow.com","user_id":1849664,"reputation":4220,"account_id":1703573,"creation_date":1353769269,"badge_counts":{"gold":8,"silver":12,"bronze":36},"last_access_date":1375455434,"answer_count":242,"question_count":26},{"site_name":"Server Fault","site_url":"http://serverfault.com","user_id":162327,"reputation":117,"account_id":1703573,"creation_date":1362072291,"badge_counts":{"gold":0,"silver":0,"bronze":9},"last_access_date":1374722580,"answer_count":0,"question_count":4},...
And I get the correct JSON with this code:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://api.stackexchange.com/2.1/me/associated?key=__SECRET_KEY_:)__&access_token=%#", [[NSUserDefaults standardUserDefaults] objectForKey:#"token"]]];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
if (jsonData)
{
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
}
When I manually invalidate the token, however, the URL still looks the same, and the page in a browser displays this:
{"error_id":403,"error_name":"access_denied","error_message":"`key` is not valid for passed `access_token`, token not found."}
However, dataWithContentsOfURL: is always nil. Why? What am I doing wrong?
I do get an NSError returned:
Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)" UserInfo=0x1dd1e9f0 {NSURL=https://api.stackexchange.com/2.1/me/associated?key=key((&access_token=token))}
NSCocoaErrorDomain Code=256 actually means a "file system or file I/O related error whose reason is unknown".
Why you get this error is likely because using dataWithContentsOfURL: will not work with that remote URL - or maybe because of the query params which contain the authentication and the token. Thus, you get the "weird" error.
In general, NSData's dataWithContentsOfURL: should only be use to access local file resources.
In order to solve your problem, you should improve your code in two steps:
1) Use NSURLConnection's convenient class method
+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
The block defines what to do with the response data when the request finished. Generally, first check the error parameter, then status code of the response and Content-type - in this order.
2) Replace the former with your own instance method (or one from a third party) with a similar signature but which is much more sophisticated.
Approach #2 enables you to implement and use the following important features
Cancellation
customize authentication in every aspects
load body data to files
process received chunks simultaneous
perform multiple requests in a queue which controls the number of simultaneous connections
and a couple more.
Approach #2 is oftentimes implemented as a subclass of NSOperation and encapsulates a NSURLConnection object (which you need to cancel the connection).
You'll find answers of how to use NSURLConnection in asynchronous mode implementing the delegates. Also, there are third party solutions.
You might find the official documentation invaluable, too:
Using NSURLConnection
For a quick start, you may take a look at my "Simple GET request" class on Gist:
SimpleGetHTTPRequest
This class is NOT based on NSOperation, but it can be modified easily. Consult the official documentation of NSOperation how to make a subclass. This is basically easy, but has a few important things (KVO) which you should get correct.
In my case, adding AppTransportSecuritySettings dictionary into info.plist and setting key AllowArbitraryLoads to true.
Fixed my problem...
Hope it helps new developers.
Your URL might be having a space that's why it returns nil.Just replace the space in URL with a '+' :
stringByReplacingOccurrencesOfString:#" " withString:#"+"
I had this problem when I changed my folder structure. It gave me other NSError codes such as 512 and 4 for any file operations (local and web). The solution was to delete my IOS Simulator folders (Library\Developer\CoreSimulator).
If you are trying to access a remote url via HTTP and using XCode 7 or later you may get a NSCocoaErrorDomain returned from [NSData dataWithContentsOfURL:].
The root cause of this may actually be your "App Transport Security Settings". By default iOS doesn't allow arbitrary loading of URLS.