AVAudioSession sharedInstance requestRecordPermission:^(BOOL granted) - iphone

Here is my code:
-(void) recordButton{
[[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
NSLog(#"value of the grant is :: %hhd", granted);
if (granted)
{
// perform operation recording
// perfrom some operation on UI(changing labels and all)
}
else
{
// do operation
}
}];
}
Problem is, when i run my app for the first time , after reset in the privacy and my app calls the above defined method, it creates trouble.
when My app run for the first time, allow/disallow microphones messgae(OS defined) method pops up.
when i click allow it displays the boolean(granted correclty). Goes inside IF correctly. Starts the recording correctly. but the UI freezes. and the second part of IF i.e changing label names, doesnt execute till , a timer (added by me stops the method and recording) executes.
PLease help.
I can sense that my 2nd part of the IF(changing UI label are not working in foreground), i.e. background work is working perfectly. Please Help, I am not expert. started iOS programing 2 months back.

I got the answer. my problem was, that when program reached If(granted) ,
it was performing the recording function but didn't performed on UI(changing labels and all).
The problem was, that the whole code was treated as a separate thread and was performed in background.
That's why recording was working properly(as it was a background process).
But UI(changing the labels) was a foreground task.
So For that, I had to execute the UI CODE under a thread that was on MAIN queue. And now it works perfectly.

AVAudioSession's requestRecordPermission callback is a background thread. Using code on the main thread inside a background thread causes issues (and most likely a crash).
You should call a method on the main thread to execute any post granted code. Using performSelectorOnMainThread: is an excellent way to make sure your code is running on the main thread (as explained here: execution on main thread).

Related

how to upload image in background in swift using GCD

i used the following code to upload image to server in background
var queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
dispatch_async((queue), {
self.StartUploadProcess()//upload function
})
the above code run perfectly in simulator but when i test the application on my iPad it will stop the background execution when user click home button or open other application
please help me so i can run the application even the user click on home button?
The point of dispatch_sync() is to run the code in another thread synchronously. There is also dispatch_async() which runs asynchronously, that is, in the background.
From your question I assume you already know how to run it when you want to, just need to make it into an async call.

What does "UIBackgroundTaskInvalid" mean?

I'm developing iPhone app which runs in the background(iOS4), and refer "Completing a Finite Length Task in the Background" written by Apple at the following url
http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH5
Then I've been able to implement background tasks.
(Of course, I see that application has 10min time limitaiton.)
However, I still can't understand what "bgTask = UIBackgroundTaskInvalid;"(Line7,16 of Listing 4-2) means.
In my opinion, the line shown above has never been reached.
Because there is "endBackgroundTask:" before that and the background task will be ended.
In fact, when I checked with xcode debugger, this thought may be true and not reach at Line7, 16.
If so, is this line redundant?
Or is there any reason to have to be written?
I would appreciate any help about this.
Thanks in advance.
The code in the block is called if the 10 minutes runs out before the application has completed its background task.
The code in this block must call endBackground: to indicate the situation is acknowledged and accepted by the application - if it doesn't the application will be terminated. Note that calling the method doesn't terminate the application - it simply indicates to the OS that the background task execution has completed.
The second line is simply to reset bgTask to a neutral value, rather than leaving it set id of a task that no longer exists. It's a tidiness thing rather than being essential.
(I wouldn't be surprised if the second line isn't executed until the application is next foregrounded, since once background execution ends the app doesn't get any CPU time to run. Haven't tested this, though)
Key to understanding it is that instead of having a completionHandler you have an expirationHandler. It only executes that line as a 'clean up' of your code taking toooo long.
To clean up it has nuke/kill/end your background task. So first it has to stop it with:
[application endBackgroundTask:bgTask];
Then it also sets a flag on the task so it won't be executed again.
bgTask = UIBackgroundTaskInvalid;
The reason you see it twice in the code is because either:
It successfully runs in the background and gets finished in the dispatch block...so you need to inform the app that hey I'm done.
You don't finish in the background but the app is like times up! You gotta go...clean up after yourself by doing a [application endBackgroundTask:bgTask]; + bgTask = UIBackgroundTaskInvalid;

NSFileManager: Continue writing to disk in background?

in my iPhone app, I am using the default NSFileManager to copy and move some data around. The amount of data may be some MB, so it may take several seconds to finish copying. If the user now starts a copy process and quits the application, can I continue writing to disk in background mode? If so, how? I do not want to start a new copy process, but only finish the running one.
I am currently using two kinds of method calls:
[imageData writeToFile:path atomically:YES];
and
[fm copyItemAtPath:sourcePath toPath:destinationPath error:&error];
Both calls are wrapped in another method and are performed in the background via -performSelectorInBackground:withObject:.
Another question is if I can get any information on how far the writing operation has progressed or at least if it has already finished?
EDIT: Some more information:
Currently, I did not implement any background tasks at all. What happens to running disk operations when the user presses the home button? Are they just cut off and the file is incomplete? Can I continue writing on the next start? Are they canceled and the incomplete file is removed?
To sum it all up: I am writing data to disk and I want it to stay consistent when the user presses the home button during a writing operation. How do I achieve this?
By default you app does not really finishes when the user press the home button. Hence it should finish the that task as long is does not take too long. If it takes long then please take a look at this question: How to implement Task completion
One thing: I think you are confused about what performSelectorInBackground:withObject: really does.
The background used in "... I continue writing to disk in background mode" and the background in "performSelectorIn Background :withObject: " are not the same background
The former background:
Is when you app becomes invisible to the user, but is still running, at least for a while. (When the user presses twice the home button and change to another app)
The latter background:
Refers to a background thread, which is the opposite to the main thread.
In this case, if you use or not performSelectorInBackground:withObject: it will have no effect in whether you app can do it background mode or not. These are completely different things
You can set BOOL finished = YES right after [fm copyItemAtPath:ToPath:error:]; and save it in NSUserDefaults and check that flag when your app comes to the foreground again ;)
Hope it helps ;)
You may want to look into NSOperationQueue, the documentation page is here.
Also there are two existing Stack Overflow questions that address using NSOperationQueue that are here and here. Both have accepted answers.
As for figuring out whether a file write has completed, I had this issue as well when I was writing an OS X application that created a very large file. I wanted the user to be able to track the progress of the write. I ended up using an NSTimer along with a UIProgressBar
Essentially, you will want to determine the (expected) total size of the file. Then, as you write the file, you should have another method (in the code below I have checkFileWritingProgress) that you can call at periodic intervals using an NSTimer. Check the current progress against the total expected file size and update the UIProgressBar accordingly.
I have provided some code to get you started.
- (void)checkFileWritingProgress:(NSTimer *)someTimer {
fileAttributes = [fileManager attributesOfItemAtPath:[NSString stringWithFormat:#"%#.data",saveLocation] error:nil];
currentFileSize = [fileAttributes fileSize]; // instance variable
if(currentFileSize < maxFileSize) { // maxFileSize is instance variable
[progressBar setDoubleValue:(((double)currentFileSize/(double)maxFileSize)*100)];
// progressWindows OS X only... not on iOS
//[progressWindow setTitle:[NSString stringWithFormat:#"Writing... | %.0f%%",(((double)currentFileSize/(double)maxFileSize)*100)]];
}
else {
[progressBar setDoubleValue:100.0];
}
}
And the timer...
NSTimer *timer = [[NSTimer scheduledTimerWithTimeInterval:0.01
target:self
selector:#selector(checkFileWritingProgress:)
userInfo:nil
repeats:YES] retain];
//(linked to timer... this is the
// CORRECT way to use a determinate progress bar)
[progressBar setIndeterminate:NO];
[progressBar setDoubleValue:0.0];
[progressBar displayIfNeeded];
I hope this code helps. Let me know if anything needs to be clarified.

How to use NSOperation and NSOperationQueue

I made an app which plays the song on clicking on the image of artist.(see image attached). Each artist image is implemented on button and on clicking this button, a function is being called which first downloads and then plays the song. I passed this method(function) in a thread but problem is that every time when I click on the image of artist(button) new threads starts running and then multiple songs gets started playing concurrently. How can I use "NSOperation and NSOperationQueue" so that only one song will run at a time . Please help.
Thanks in advance
NSOperation and NSOperationQueue aren't going to directly solve your problem.
If I were pursuing a dead simple approach, I would have a global AudioPlayer object that has a method startPlaying: whose argument is the song to play (represented however needed; URL, NSData, whatever you need).
In that method, I'd stop playing whatever is currently playing and start the new track.
If I remember correctly, I don't think you even need a thread for this; the audio APIs are generally quite adept at taking care of playback in the background.
In any case, if you do need a thread, then I'd hide that thread in my AudioPlayer object and let it take care of telling the music to stop/start playing in said thread. A queue of some kind -- operation or GCD -- could be used for that, yes.

What happens to an iPhone app when iPhone goes into stand-by mode?

My app uses NSTimer and it appears that NSTimer doesn't fire when the iPhone goes into the stand-by mode (either by pressing the hardware button or by the idle timer).
When I activate the iPhone again, my app is still in the foreground. What happens to third party apps when the iPhone is the stand-by mode?
Although it's not evident here, I believe the original poster did find an answer to his question by starting a thread (available here) in the iPhone Developer Forums (which I eventually had to find myself because the information wasn't shared here).
In case someone else has the same question and finds the page in the future, here's a helpful response that was posted by someone on the Apple forum called "eskimo1" (which I have edited slightly such that it is easier to read without having the context provided by the entire original thread):
Regarding iPhone app status terminology, "active" does not mean "awake", it means "attached to the GUI". Think of it being analogous to "frontmost" in Mac OS X. When you lock the device your app deactivates but the device may or may not go to sleep
iPhone OS rarely sleeps if the device is connected to main power (i.e., via USB). It can sleep if running on battery, however.
A short time after the screen is locked (20 seconds according to Oliver Drobnik), the device sleeps. This is like closing the lid on your laptop; all activity on the main CPU halts.
This does not happen if the device is playing audio in the right audio session. See DTS Q&A QA1626 "Audio Session - Ensuring audio playback continues when screen is locked" for details.
Note that the idleTimerDisabled property (which can be turned on to prevent the screen from turning off while the app is running) is about locking the screen after user inactivity. It's not directly related to system sleep (it's indirectly related in that the system may sleep shortly after it's locked).
See Application Interruptions in the iPhone OS Programming Guide, especially the applicationWillResignActive and applicationDidBecomeActive events. (The whole guide is certainly worth reading.) When You ignore the events, the timer seems to go on for a while and then stops. Sounds logical, the application could easily drain the battery if kept running. And what exactly happens to the application? I guess it simply does not get any CPU time – it freezes and only thaws when You turn the machine back β€œon.”
My first advice is do not disable the idle timer, that is just a hack. If you want to keep a timer alive during UI events run the timer on the current run loop using NSCommonModes:
// create timer and add it to the current run loop using common modes
self.timer = [NSTimer timerWithTimeInterval:.1 target:self selector:#selector(handleTimer) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
I used the information on this post for a small sample that I was building. This is the code that I used when I initiated the playback to prevent the audio from stopping:
AudioSession.Category = AudioSessionCategory.MediaPlayback;
And when the application is done with the playback to reset to the original value:
AudioSession.Category = AudioSessionCategory.SoloAmbientSound;
The full sample is here:
http://github.com/migueldeicaza/monotouch-samples/tree/master/StreamingAudio/
I was faced with this issue recently in an app I am working on that uses several timers and plays some audio prompts and made two relatively simple changes:
In the AppDelegate I implemented the following methods and there mere presence allows the app to continue when the screen is locked
// this receives the notification when the device is locked
- (void)applicationWillResignActive:(UIApplication *)application
{
}
// this receives the notification that the application is about to become active again
- (void)applicationWillBecomeActive:(NSNotification *)aNotification
{
}
references: UIApplicationDelegate Protocol Reference & NSApplication Class Reference in the API doc (accessible via Xcode, just search for applicationWillBecomeActive).
Made the main viewcontroller class an AVAudioPlayerDelegate and used this code from Apple's "AddMusic" sample to make the audio alerts the app played mix nicely into the iPod audio etc...
I just dropped this code into a method that is called during viewDidLoad. If this interests you, you fall into the "who should read this doc" category for this: Audio Session Programming Guide
// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setDelegate: self];
// The AmbientSound category allows application audio to mix with Media Player
// audio. The category also indicates that application audio should stop playing
// if the Ring/Siilent switch is set to "silent" or the screen locks.
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
// Activates the audio session.
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
I believe your application should run normally when suspended. (think Pandora Radio)
Check to see if your timer is being deallocated due to your view being hidden or some other event occurring.