OSStatus error -50? - iphone

I just received a result code(-50) returned from ExtAudioFileWrite().
And I didnt't find the information about this result code in "Extended Audio File Services Reference".
Please help me to resolve it.
Thanks.

This error code is declared in MacErrors.h of the CarbonCore framework. -50 is paramErr. IOW, one of your parameters is invalid. So you will need to verify your parameters, buffer sizes, arguments that you pass and so on to locate the parameter which has been flagged.

Add the code to the initialization of project
NSArray *availableInputs = [[AVAudioSession sharedInstance] availableInputs];
AVAudioSessionPortDescription *port = [availableInputs objectAtIndex:0]; //built in mic for your case
NSError *portErr = nil;
[[AVAudioSession sharedInstance] setPreferredInput:port error:&portErr];

errSecParam = -50, /* One or more parameters passed to a function were not valid. */
you can find all error in Security->SecBase.h

Related

Write stderr on iPhone to both file and console

I'm following the suggestion in the answer here for redirecting NSLog output on an iOS device to a file, which works great. The problem is that it no longer shows up in the console on the device. What I'd really like is a way to tee the stderr stream to both the console and the file. Does anyone have an idea how to do that?
I found an acceptable answer on another thread (NSLog() to both console and file).
The solution provided there is to only redirect to a file if a debugger is not detected, like this:
if (!isatty(STDERR_FILENO))
{
// Redirection code
}
Thanks to Sailesh for that answer.
Once you freopen() the file descriptor, you can read from it and do as you please with the data. Some ideas from this will be useful to you.
You could either write it back out to stdout, or try to write directly to /dev/console. I've never tried to open /dev/console on an iPhone, but I'm guessing it's possible despite being outside of the sandbox. I'm not sure how the app review process will treat it.
Or you can redirect to a TCP socket and view on a remote telnet client. No need for XCode this way!
Basically:
Create a standard C function which calls an Obj-C static method:
void tcpLogg_log(NSString* fmt, ...)
{
va_list args;
va_start(args, fmt);
[TCPLogger tcpLog:fmt :args];
va_end(args);
}
The static Obj-C method:
(void)tcpLog:(NSString*)fmt :(va_list)args
{
NSLogv(fmt, args);
if(sharedSingleton != nil && sharedSingleton.socket != nil)
{
NSString *time = [sharedSingleton.dateFormat stringFromDate:[NSDate date]];
NSString *msg = [[NSString alloc] initWithFormat:fmt arguments:args];
mach_port_t tid = pthread_mach_thread_np(pthread_self());
NSString *str = [NSString stringWithFormat:#"%#[%X]: %#\r\n", time, tid, msg];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[sharedSingleton.socket writeData:data
withTimeout:NETWORK_CLIENT_TIMEOUT_PERIOD
tag:0];
}
}
Then in your .pch file, add the following lines to override NSLog()
define NSLog(...) tcpLogg_log(__VA_ARGS__);
void tcpLogg_log(NSString* fmt, ...);
Of course more details are required to handle the TCP Socket. Working source code is available here:
https://github.com/driedler/iOS-TCP-Logger/wiki/About

Sending data error?

typedef struct _protocol1
{
int type;
CGPoint pos;
} Protocol1;
-(void)sendData {
NSError *error;
Protocol1 msg;
msg.pos = ccp(100,100);
msg.type = 1;
NSData *packet = [NSData dataWithBytes:&msg length:sizeof(Protocol1)];
[self.myMatch sendDataToAllPlayers: packet withDataMode: GKMatchSendDataReliable error:&error];
if (error != nil)
{
NSLog(#"error"]);
}
}
That is a chunk of code from my project.
And I'm getting an error. However, I am unsure how to retrieve more information to help me debug. Can someone help me?
Sorry, I'm quite new with iOS development...
Using Cocos2d for a game.
EDIT
I am using the Simulator and my iPhone to test this. I doubt that is the problem, I already got the match working and everything...
To print out your error, try this!
NSLog(#"here is the error material: %#", [error localizedDescription])
if you have trouble, just click on NSError in your XCode4.
Then look at the right column, and click to get to the documentation.
(Or just search "NSError" in the Xcode documentation.)
Bring up "NSError Class Reference". It is very simple.
Be sure to look at the VARIOUS EXAMPLE CODE given.
For example scroll down to "localizedDescription" ad see the three sample codes. ("LazyTableImages, SeismicXML, URLCache")
You can download and look at the example projects. Search on "localizedDescription" and you'll see examples, if you're having trouble!
If you teach a man to fish ... Lol have fun.

Incorrect NSStringEncoding value 0x0000 detected

I am using ASIHttpRequest library in iphone and when i try to do a GET request on the below URL i get this message and the request fails, please anyone if he/she has encountered this problem or know a possible solution to it please let me know. Secondly if i paste the link in the browser it works perfectly fine.
[URL]
http://www.rugsale.com/iphone/app/?type=product_list&params=id%3D334&ver=1.0&key=kaoud
[ERROR]
Incorrect NSStringEncoding value 0x0000 detected. Assuming NSStringEncodingASCII. Will stop this compatiblity mapping behavior in the near future.
Thx in advance
Regards
Syed Arsalan Pervez
www.saplogix.net
This notably happens if you call [asiHttpRequest getResponseString] before a valid response has been returned and the request encoding has been set (i.e. couldn't connect to server).
The easiest way to workaround this warning is by editing the ASIHTTPRequest class, remove the #synthesize responseEncoding and adding a simple custom getter/setter so you can return the default encoding if the response encoding isn't set:
- (NSStringEncoding) responseEncoding
{
return responseEncoding || self.defaultResponseEncoding;
}
- (void) setResponseEncoding:(NSStringEncoding)_responseEncoding
{
responseEncoding = _responseEncoding;
}
There's also a more specific workaround for the getResponseString method, which I think is the only place that uses the encoding without checking for a value - since the encoding should be set for any non-zero length response:
- (NSString *)responseString
{
NSData *data = [self responseData];
if (!data) {
return nil;
}
// --- INSERT THIS BLOCK ---
// If the 'data' is present but empty, return a simple empty string
if (data.length == 0) {
return #"";
}
//assert(self.responseEncoding); // if you're into runtime asserts, uncomment this
// --- END OF BLOCK TO INSERT ---
return [[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:[self responseEncoding]] autorelease];
}
For me the problem was timeout wasn't enough. So it returns an empty response. So it gives this error because you'r trying to do something with an empty response. I increased the time for it. So it solved my problem.[request setTimeOutSeconds:200];
this is just saying that the encoding was nil, when a value was expected. Try doing a search for "encoding:nil" or "encoding:NULL" in your source code and replace it with a valid encoding, for example NSStringEncodingASCII...
This looks like something that's cropped up in the 4.2 SDK. I didn't see this until I updated my development environment myself.
All-Seeing Interactive will probably have to update the code to ensure compatibility.
The error is where you are creating a string. You don't supply an encoding which is required.

Improper Return Value using NSFileManager createDirectoryAtPath:

I'm working on a new feature for an existing iPhone application, and would like to create several new directories in the application's local "Documents" folder. I have successfully done this using the recommended method:
[NSFileManager createDirectoryAtPath:withIntermediateDirectories:attributes:error:]
When reading the documentation for this method, I was intrigued by return values listed in Apple's official documentation:
Return Value:
YES if the operation was successful or already exists, otherwise NO
Each time my application starts up, I would like to ensure that the directories are properly in place. I thought a clever way of doing this would be to call the createDirectory: method on each start and take advantage of the method's return value. If the directory was missing for some reason, it would be created. If the directory was already in place, the return value would still be YES. A NO return value could then be used as a flag for additional recovery/repair logic.
Unfortunately, I appear to be getting results inconsistent with Apple's documentation. The method is returning NO if the directory already exists - when Apple's docs say it should return YES in this case.
The following program demonstrates this behavior:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSFileManager * fm = [NSFileManager defaultManager];
bool testDirectoryCreated = NO;
testDirectoryCreated = [[NSFileManager defaultManager]createDirectoryAtPath: [NSString stringWithFormat:#"%#/%#",[fm currentDirectoryPath],#"TestDirectory"]
withIntermediateDirectories: NO
attributes: nil
error: NULL];
NSLog(#"TestDirectory Created: %#\n", (testDirectoryCreated ? #"YES" : #"NO"));
testDirectoryCreated = [[NSFileManager defaultManager]createDirectoryAtPath: [NSString stringWithFormat:#"%#/%#",[fm currentDirectoryPath],#"TestDirectory"]
withIntermediateDirectories: NO
attributes: nil
error: NULL];
NSLog(#"TestDirectory Created: %#\n", (testDirectoryCreated ? #"YES" : #"NO"));
[pool drain];
return 0;
}
When the program executes, it will print YES on the first createDirectory: call, and NO on the second call - when "TestDirectory" already exists.
Is this an error in Apple's documentation, or am I missing something?
Also, any other ideas for just validating the integrity of my directory structure? Is there a simple "directory exists" method I can call?
Thanks,
Tom
If you'd like to get the convenience to also check if the directory exists with this method, you must pass TRUE to the withIntermediateDirectories: parameter.
This is stated in Apple's documentation
In addition, if you pass NO for this parameter, the directory must not exist at the time this call is made.
It does seem odd to me that the return value would be YES, if the directory already exists. I would have expected this return Value to only reflect success on creating the dir. Which would be consistent to your returns.
As to your other question, you may want to look at fileExistsAtPath: and fileExistsAtPath:isDirectory: under the NSFileManager.

iphone Core Data Unresolved error while saving

I am getting a strange error message from the core data when trying to save
but the problem that the error is not reproducible ( it appears at different times when doing different tasks)
the error message:
Unresolved error Domain=NSCocoaErrorDomain Code=1560 UserInfo=0x14f5480 "Operation could not be completed. (Cocoa error 1560.)", {
NSDetailedErrors = (
Error Domain=NSCocoaErrorDomain Code=1570 UserInfo=0x5406d70 "Operation could not be completed. (Cocoa error 1570.)",
Error Domain=NSCocoaErrorDomain Code=1570 UserInfo=0x14f9be0 "Operation could not be completed. (Cocoa error 1570.)"
);
}
and the method that generates the error is:
- (IBAction)saveAction:(id)sender {
NSError *error;
if (![[self managedObjectContext] save:&error]) {
// Handle error
NSLog(#"Unresolved error %#, %#, %#", error, [error userInfo],[error localizedDescription]);
exit(-1); // Fail
}
}
any idea for the reason of this message ? giving that it appears at random times
It means there's a mandatory property has been assigned nil. Either in your *.xcodatamodel check the "optional" box or when you are saving to the managedObjectContext make sure that your properties are filled in.
If you're getting further errors after changing your code to suit the two requirements try cleaning your build and delete the application from your iPhone Simulator/iPhone device. Your model change may conflict with the old model implementation.
Edit:
I almost forgot here's all the error codes that Core Data spits out:
Core Data Constants Reference
I had trouble with this before and I realised I unchecked the correct optional box. Such trouble finding out the problem. Good luck.
I struggled with this for a little while myself. The real problem here is that the debugging you've got isn't showing you what the problem is. The reason for this is because CoreData will put an array of NSError objects in the "top level" NSError object it returns if there is more than one problem (This is why you see error 1560, which indicates multiple problems, and an array of error 1570s). It appears that CoreData has a handful of keys it uses to stash information in the error it returns if there is an issue that will give you more useful information (Such as the entity the error occurred on, the relationship/attribute that was missing, etc). The keys you use to inspect the userInfo dictionary can be found in the reference docs here.
This is the block of code I use to get reasonable output from the error returned during a save:
NSError* error;
if(![[survey managedObjectContext] save:&error]) {
NSLog(#"Failed to save to data store: %#", [error localizedDescription]);
NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
if(detailedErrors != nil && [detailedErrors count] > 0) {
for(NSError* detailedError in detailedErrors) {
NSLog(#" DetailedError: %#", [detailedError userInfo]);
}
}
else {
NSLog(#" %#", [error userInfo]);
}
}
It will produce output that tells you the fields that are in missing, which makes fixing the problem significantly easier to deal with.
I'm throwing this in as an answer, even though it's really more of an embellishment to Charles' snippet. The straight output from NSLog can be a mess to read and interpret, so I like to throw in some white space and call out the value of some critical 'userInfo' keys.
Here's a version of the method I've been using. ('_sharedManagedObjectContext' is a #define for '[[[UIApplication sharedApplication] delegate] managedObjectContext]'.)
- (BOOL)saveData {
NSError *error;
if (![_sharedManagedObjectContext save:&error]) {
// If Cocoa generated the error...
if ([[error domain] isEqualToString:#"NSCocoaErrorDomain"]) {
// ...check whether there's an NSDetailedErrors array
NSDictionary *userInfo = [error userInfo];
if ([userInfo valueForKey:#"NSDetailedErrors"] != nil) {
// ...and loop through the array, if so.
NSArray *errors = [userInfo valueForKey:#"NSDetailedErrors"];
for (NSError *anError in errors) {
NSDictionary *subUserInfo = [anError userInfo];
subUserInfo = [anError userInfo];
// Granted, this indents the NSValidation keys rather a lot
// ...but it's a small loss to keep the code more readable.
NSLog(#"Core Data Save Error\n\n \
NSValidationErrorKey\n%#\n\n \
NSValidationErrorPredicate\n%#\n\n \
NSValidationErrorObject\n%#\n\n \
NSLocalizedDescription\n%#",
[subUserInfo valueForKey:#"NSValidationErrorKey"],
[subUserInfo valueForKey:#"NSValidationErrorPredicate"],
[subUserInfo valueForKey:#"NSValidationErrorObject"],
[subUserInfo valueForKey:#"NSLocalizedDescription"]);
}
}
// If there was no NSDetailedErrors array, print values directly
// from the top-level userInfo object. (Hint: all of these keys
// will have null values when you've got multiple errors sitting
// behind the NSDetailedErrors key.
else {
NSLog(#"Core Data Save Error\n\n \
NSValidationErrorKey\n%#\n\n \
NSValidationErrorPredicate\n%#\n\n \
NSValidationErrorObject\n%#\n\n \
NSLocalizedDescription\n%#",
[userInfo valueForKey:#"NSValidationErrorKey"],
[userInfo valueForKey:#"NSValidationErrorPredicate"],
[userInfo valueForKey:#"NSValidationErrorObject"],
[userInfo valueForKey:#"NSLocalizedDescription"]);
}
}
// Handle mine--or 3rd party-generated--errors
else {
NSLog(#"Custom Error: %#", [error localizedDescription]);
}
return NO;
}
return YES;
}
This allows me to see the value for 'NSValidationErrorKey', which, when I encountered the issue from the OP, pointed directly to the non-optional Core Data entities that I'd forgot to set before trying to save.
The problem touched me, when I save second record to CoreData.
All not optional fields (relationship) was filled without nil as well, but in the error output I'd notice, that one of fields in first saved object had became nil. Strange a little? But the reason is quite trivial - one to one relationship which nullify first object, when I set it in the second.
So, the scheme is:
"Parent" with relationship "child" One to One
Create Child 1, set parent. Save - OK
Create Child 2, set parent. Save - Error, Child 1.Parent == nil
(behind the scene child 2 did nullify child 1 parent)
Changing the relationship in Parent from One to One to Many to One solved this task.
I had transient property of type int that wasn't optional. Obviously, when it was set to 0, 1570 error appear. Just changed all my transient properties to optional. Nil-check logic can be implemented in code if necessary.
I means that your model failed to validate, which could happen for a number of reasons: unused property in your model, missing value that's marked as required.
To get a better understanding of what exactly went wrong, put a breakpoint in a place where you are ready to save your object, and call one of the validateFor... method variants, like:
po [myObject validateForInsert]
More detailed information about the problem is in error description. Successful validation means you will get no output.
It helped me. Check this one too.
Check the optional box in your *.xcodatamodel objects