presentMediaPlayerControllerWithURL dismissing immediately without playing the audio - objective-c

I'm creating a watch application which records an audio and play that audio. The recorded audio is saved in the Apps Groups and I used the following code for playing the audio.
- (void)playAudio
{
// Playing the audio from the url using the default controller
[self presentMediaPlayerControllerWithURL:self.audioFileURL options:#{WKMediaPlayerControllerOptionsAutoplayKey : #YES} completion:^(BOOL didPlayToEnd, NSTimeInterval endTime, NSError * _Nullable error) {
NSLog(#"Error = %#",error);
}];
}
Unfortunately I am getting the following error and the player controller get dismissed immediately.
Error Domain=com.apple.watchkit.errors Code=4 "The operation could not be completed" UserInfo={NSLocalizedFailureReason=An unknown error occurred (1), NSUnderlyingError=0x16daa810 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}, NSLocalizedDescription=The operation could not be completed}.
Then I downloaded a sample project (WatchKitAudioRecorder Sample code) from Apple WatchOS Developer library but they are also having the same issue. I don't know why this is not working even in Apple Sample code :(

Finally I found that the data is not writing to the url path. Also should be written in the following path: Library/Caches/filename.extension
Here is a sample code, which may help someone.
- (void)writeAudioToAppGroupsWithData:(NSData *)audioData
{
// Writing the audio data to the App Groups
NSURL *containerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:APP_GROUP_IDENTIFIER];
containerURL = [containerURL URLByAppendingPathComponent:[NSString stringWithFormat:DIRECTORY_PATH]];
[audioData writeToURL:containerURL atomically:YES];
}
In this case make sure that your DIRECTORY_PATH is Library/Caches/filename.extension. Eg: Library/Caches/Audio.mp3

Related

NSFileHandle Cocoa Error 3

So I have a user drop some files into my application. Later I'm handling these files using NSFileHandle like this:
NSFileHandle *inputFile = [NSFileHandle fileHandleForReadingFromURL:path error:&error];
if(inputFile == nil) {
NSLog(#"Error (2): %#",error);
return;
}
On my Mac it works, but on other devices this error occurs:
Error Domain=NSCocoaErrorDomain Code=3 "The operation couldn't be completed. (Cocoa error 3.)" ...
I have looked into FoundationErrors.h but there is no error code 3 and i couldn't find anything useful using google.
What is causing this error (the description doesn't give much detail) and how can i prevent it?

NSURLErrorDomain Error Code -1005

I'm working on the CS193p coursework from Stanford (I'm not a Stanford student I'm just trying to learn), assignment number 5, where we have to get images from Flickr using calls to the Flickr api. I'm only trying to download a list of the pictures and print them out to the console, but I'm getting an NSURLErrorDomain with code -1005. The error message I am printing out is below:
error: Error Domain=NSURLErrorDomain Code=-1005 "The operation couldn’t be completed. (NSURLErrorDomain error -1005.)" UserInfo=0x7f9449c83df0 {NSErrorFailingURLStringKey=https://api.flickr.com/services/rest/?method=flickr.places.getTopPlacesList&place_type_id=7&format=json&nojsoncallback=1&api_key=4f9c3155b34836b2ac15318d98b93f3a, NSErrorFailingURLKey=https://api.flickr.com/services/rest/?method=flickr.places.getTopPlacesList&place_type_id=7&format=json&nojsoncallback=1&api_key=4f9c3155b34836b2ac15318d98b93f3a, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=57, NSUnderlyingError=0x7f9449c7fca0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1005.)"}
The Flickr API call is happening in the following method:
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration]];
NSURLSessionDownloadTask *downloadTask = [urlSession downloadTaskWithURL:[FlickrFetcherHelper URLforTopPlaces] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
NSArray *topPlaces;
if (!error) {
topPlaces = [[NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:location] options:0 error:&error] valueForKeyPath:FLICKR_RESULTS_PLACES];
}
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(topPlaces, error);
});
}];
[downloadTask resume];
I'm using xCode 6, not sure if that has anything to do with the problem. The same code was working a couple days ago, and I don't think I changed anything that would mess it up, but it clearly has.
Are you using the iOS8 (iPhone 6 for example) simulator? If so, try changing to iPhone 5s. I was having the same problem and switched my simulator and all worked well again. I tried this after reading the following feedback: https://github.com/AFNetworking/AFNetworking/issues/2314
Switch to iOS Simulator and do "Reset Content and Settings ..." from top menu.

AFNetworking Half the time downloading half the data

I'm trying to download a small file, about 5.5kb.
Half of the time it only downloads half of the json, and then of course fails parsing that data. The other half of the time everything works completely normal.
I have a good internet connection.
Im using AFNetworking 2.0. I got it off of the main branch today (1/16/2014).
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:[NSString stringWithFormat:#"%#Physicians/Types/?os=1",BaseUrl] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
NSLog(#"Error: %#", operation.responseString);
}];
Here is the exact error, but i already know its a parsing error:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (No string key for value in object around character 4480.) UserInfo=0x15ecd010 {NSDebugDescription=No string key for value in object around character 4480.}
This is the sample from their website. And like I said it works half of the time.
Do I need to set some sort of chunk size? Is it because their Github page says the current build is failing?
Interestingly enough, it seems to always fail at the exact same point in the file. I can tell this because in the error, I output the response string.
I am not able to reproduce this in any browser, or in my old app which used asihttprequest
***Update 1/28/2014
I downloaded the current version today, which is passing build, and it still fails. When I save out to disk what it does receive it's 5,391 bytes. Again, it fails at the same point each time. In the middle of the work dentist. There aren't any weird characters there.

Can create, but not open, a UIManagedDocument with iCloud support

I am creating a new UIManagedDocument with iCloud support as follows:
Alloc and init with local sandbox URL
Set persistent store options to support iCloud: ubiquitousContentNameKey and ubiquitousContentURL. The name I'm generating uniquely and the URL is pointing to my ubiquityContainer / CoreData.
Save locally to sandbox with UIManagedDocument's saveToURL method.
In completion handler, move to iCloud with FileManager's setUbiquitous method.
So far, this dance works. (Well, sort of). After I call setUbiquitous, I get an error that says it WASN'T successful, however the document moves to the cloud. When it's done, I have a new document in the cloud. This appears to be a bug, as I've been able to replicate it with others' code.
I'm actually generating this document in a "Documents View Controller," which lists all of the documents in the cloud. So when this new document's final completion handler is finished, it shows up in the table view thanks to an NSMetadataQuery. So far, pretty standard usage I think.
To edit a document, the user taps and goes to a "Single View Document View Controller."
In this view controller, I need to "reopen" the selected document so the user can edit it.
So I go through series of steps again:
Alloc / init a UIManagedDocument with a fileURL -- this time, the URL is from the cloud.
Set my persistent store options, same as step 2 above, with same settings.
Now, I ATTEMPT step 3, which is to open the document from disk, but it fails. The document is in a state of "Closed | SavingError" and the attempt to open fails.
Does anyone know why my document would create OK, move to the cloud OK, but then fail to open on an immediate subsequent attempt? (Really, an attempt within that launch of the app - see below). Specifically, what would make a UIManagedDocument instance be created but in a closed, non-openable state?
Interestingly enough, if I quit the app and launch again, I can tap and reload the document and edit it.
And very occasionally I can create, then open, and edit very briefly, say insert one managedobject, and then it goes into this close | saving error state.
ERROR INFO:
I've subclassed UIManagedDocument and overrode the -handleError: method to try and get more information, and here's what I get (along with some other debugging logs I put in):
2012-10-05 14:57:06.000 Foundations[23687:907] Single Document View Controller View Did Load. Document: fileURL: file://localhost/private/var/mobile/Library/Mobile%20Documents/7PB5426XF4~com~howlin~MyApp/Documents/New%20Document%2034/ documentState: [Closed]
2012-10-05 14:57:06.052 MyApp[23687:907] Document state changed. Current state: 5 fileURL: file://localhost/private/var/mobile/Library/Mobile%20Documents/7PB5426XF4~com~howlin~MyApp/Documents/New%20Document%2034/ documentState: [Closed | SavingError]
2012-10-05 14:57:06.057 Foundations[23687:5303] UIManagedDocument error: The store name: New Document 34 is already in use.
Store URL: file://localhost/private/var/mobile/Library/Mobile%20Documents/7PB5426XF4~com~howlin~MyApp/Documents/New%20Document%2034/StoreContent.nosync/persistentStore
In Use Store URL: file://localhost/var/mobile/Applications/D423F5FF-4B8E-4C3E-B908-11824D70FD34/Documents/New%20Document%2034/StoreContent.nosync/persistentStore
2012-10-05 14:57:06.059 MyApp[23687:5303] {
NSLocalizedDescription = "The store name: New Document 34 is already in use.\n\tStore URL: file://localhost/private/var/mobile/Library/Mobile%20Documents/7PB5426XF4~com~howlin~MyApp/Documents/New%20Document%2034/StoreContent.nosync/persistentStore\n\tIn Use Store URL: file://localhost/var/mobile/Applications/D423F5FF-4B8E-4C3E-B908-11824D70FD34/Documents/New%20Document%2034/StoreContent.nosync/persistentStore\n";
NSPersistentStoreUbiquitousContentNameKey = "New Document 34";
}
The error seems to think I'm it create a store that already exists on the subsequent opening. Am I now supposed to set those iCloud option on the persistent store on a second opening? I've tried that approach and it didn't work either.
I've studied the Stanford lectures on UIManagedDocument and don't see what I'm doing wrong.
Here's my method to create the doc and move to cloud:
- (void) testCreatingICloudDocWithName:(NSString*)name
{
NSURL* cloudURL = [self.docManager.iCloudURL URLByAppendingPathComponent:name isDirectory:YES];
NSURL* fileURL = [self.docManager.localURL URLByAppendingPathComponent:name];
self.aWriting = [[FNFoundationDocument alloc] initWithFileURL:fileURL];
[self setPersistentStoreOptionsInDocument:self.aWriting];
[self.aWriting saveToURL:fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success == YES) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//create file coordinator
//move document to icloud
NSFileCoordinator* fileCoordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
NSError* coorError = nil;
[fileCoordinator coordinateWritingItemAtURL:cloudURL options:NSFileCoordinatorWritingForReplacing error:&coorError byAccessor:^(NSURL *newURL) {
if (coorError) {
NSLog(#"Coordinating writer error: %#", coorError);
}
NSFileManager* fm = [NSFileManager defaultManager];
NSError* error = nil;
NSLog(#"Before set ubiq");
[fm setUbiquitous:YES itemAtURL:fileURL destinationURL:newURL error:&error];
if (!error) {
NSLog(#"Set ubiquitous successfully.");
}
else NSLog(#"Error saving to cloud. Error: %#", error);
NSLog(#"State of Doc after error saving to cloud: %#", self.aWriting);
}];
});
}
}];
}
Here's where I set options for iCloud on the persistentStore:
- (void)setPersistentStoreOptionsInDocument:(FNDocument *)theDocument
{
NSMutableDictionary *options = [NSMutableDictionary dictionary];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];
[options setObject:[theDocument.fileURL lastPathComponent] forKey:NSPersistentStoreUbiquitousContentNameKey];
NSURL* coreDataLogDirectory = [self.docManager.coreDataLogsURL URLByAppendingPathComponent:[theDocument.fileURL lastPathComponent]];
NSLog(#"Core data log dir: %#", coreDataLogDirectory);
[options setObject:coreDataLogDirectory forKey:NSPersistentStoreUbiquitousContentURLKey];
theDocument.persistentStoreOptions = options;
}
And here's where I try to reopen it:
- (void) prepareDocForUse
{
NSURL* fileURL = self.singleDocument.fileURL;
if (![[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]]) {
NSLog(#"File doesn't exist");
}
else if (self.singleDocument.documentState == UIDocumentStateClosed) {
// exists on disk, but we need to open it
[self.singleDocument openWithCompletionHandler:^(BOOL success) {
if (!success) {
NSError* error;
[self.singleDocument handleError:error userInteractionPermitted:NO];
}
[self setupFetchedResultsController];
}];
} else if (self.singleDocument.documentState == UIDocumentStateNormal) {
// already open and ready to use
[self setupFetchedResultsController];
}
}
Have you recently been testing various version of iOS? Try changing the title of your saved document to something other than "New Document 34", I was experiencing this same issue and I believe it had to do with conflicting documents saved from different sdk compilations of the app using the same document url.
I target iOS7, I use a single UIManagedDocument as my app DB with the goal to better integrate CoreData and iCloud as suggested by Apple in its documentation. I had the same problem, i solved with the following code.
Since I wrote it, I moved the PSC options settings inside the lazy instantiation of the UIManagedDocument.
My original code created, closed and then reopened the document using the callback with success standard functions. I found it on a book by Erika Sadun. Everything seemed ok but I couldn't reopen the just created and then closed document because it was in "savings error" state. I lost a week on it, I couldn't understand what I was doing wrong because until the reopen everything was perfect.
The following code works perfectly on my iPhone5 and iPad3.
Nicola
-(void) fetchDataWithBlock: (void (^) (void)) fetchingDataBlock
{
//If the CoreData local file exists then open it and perform the query
if([[NSFileManager defaultManager] fileExistsAtPath:[self.managedDocument.fileURL path]]){
NSLog(#"The CoreData local file in the application sandbox already exists.");
if (self.managedDocument.documentState == UIDocumentStateNormal){
NSLog(#"The CoreData local file it's in Normal state. Fetching data.");
fetchingDataBlock();
}else if (self.managedDocument.documentState == UIDocumentStateClosed){
NSLog(#"The CoreData local file it's in Closed state. I am opening it.");
[self.managedDocument openWithCompletionHandler:^(BOOL success) {
if(success){
NSLog(#"SUCCESS: The CoreData local file has been opened succesfully. Fetching data.");
fetchingDataBlock();
}else{
NSLog(#"ERROR: Can't open the CoreData local file. Can't fetch the data.");
NSLog(#"%#", self.managedDocument);
return;
}
}];
}else{
NSLog(#"ERROR: The CoreData local file has an unexpected documentState: %#", self.managedDocument);
}
}else{
NSLog(#"The CoreData local file in the application sandbox did not exist.");
NSLog(#"Setting the UIManagedDocument PSC options.");
[self setPersistentStoreOptionsInDocument:self.managedDocument];
//Create the Core Data local File
[self.managedDocument saveToURL:self.managedDocument.fileURL
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success) {
if(success){
NSLog(#"SUCCESS: The CoreData local file has been created. Fetching data.");
fetchingDataBlock();
}else{
NSLog(#"ERROR: Can't create the CoreData local file in the application sandbox. Can't fetch the data.");
NSLog(#"%#", self.managedDocument);
return;
}
}];
}
}

AVAssetReader reads audio, then fails

My app reads audio and plays it back in a producer / consumer setup. The consumer thread requests new samples to render to hardware. The producer thread reads audio data from disk into its buffer using AVAssetReader. The producer thread runs in a loop, checking if more samples need to be read. The producer's buffer size is equal to 4 seconds of audio.
When I instruct my app to buffer audio, samples are read successfully without error. When I trigger my producer thread to begin rendering audio, the 4 second buffer is played back perfectly, then silence. Further investigation reveals that my asset reader fails upon the start of playback, thus no further samples where read after the initial buffering:
CMSampleBufferRef ref = [readaudiofile copyNextSampleBuffer];
if (ref == NULL && filereader.status == AVAssetReaderStatusFailed) {
NSLog(#"reader failed: %#", filereader.error);
}
// this produces:
// {NSLocalizedFailureReason=An unknown error occurred (-12785),
// NSUnderlyingError=0x161f60 "The operation couldn’t be completed.
// (OSStatus error -12785.)", NSLocalizedDescription=The operation
// could not be completed}
My producer thread code is identical to the functional code example MusicLibraryRemoteIODemo. My consumer thread code is different, but I've compared the two line by line for a couple days and can't seem to find the hitch. Any idea what might be causing the AVAssetReader reader to fail?
This post describes similar solutions and it concluded that the Audio Session needed to be set up properly (although it doesn't say how). Is there any connection between AVAudioSesion configuration and the behavior of AVAssetReader?
I was getting this same error, I posted this answer on the other thread as well
- (void)setupAudio {
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error:&activationError];
NSLog(#"setupAudio ACTIVATION ERROR IS %#", activationError);
[[AVAudioSession sharedInstance] setPreferredIOBufferDuration:0.1 error:&activationError];
NSLog(#"setupAudio BUFFER DURATION ERROR IS %#", activationError);
}