UIProgressView not displaying progress accurately - label

I am using UIProgresView for displaying downloading and in label the percentage of content downloads.The function is executing every time. When I displaying the progress value it is showing properly in the console. But it is not displaying on the screen, It is display at only 0% and 100%. I am using ASIHTTP framework too.
Please help in that.
CODE from comment:
for (float i=0; i< [topicNew count]; i++)
{
NSDictionary *new= [topicNew objectAtIndex:i];
NSString *imageName = [[[NSString alloc] initWithFormat:#"%#.%#.%#.png", appDelegate.subject,topicNamed,[new objectForKey:kWordTitleKey]] autorelease];
NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imageName];
NSData *imageData = [self ParsingImagePath:[new objectForKey:kWordImagePathKey]];
[progressView setProgress:i/[topicNew count]];
[lblpercent setText:[[NSString stringWithFormat:#"%.0f",i/[topicNew count]] stringByAppendingString:#"%"]];
... More code here...

It looks like you are threadlocking your main thread. Meaning, you are updating the progressView but the mainthread never gets out of your for loop to display the updated change until the for loop is finished, which by then looks like your progress is set to 100%.
You need to either use a timer like (NSTimer) or some kind of background thread that processes your image files. Then you need to call your instance of UIProgressView from the background thread when you want to update your progress (end of the for loop for example)
float p = i/[topicNew count];
[progressView performSelectorOnMainThread:#selector(setProgress:)
withObject:[NSNumber numberWithFloat:p]
waitUntilDone:NO];
and pass in your updated progress to the progressView. Make sure you are not calling the progressView from the background thread directly, as UIKit is not thread safe. Only call it from your main thread, or using the performSelectorOnMainThread:withObject:waitUntilDOne: method.
Hopefully that gets you in the right directly

Related

AVAudioEngine incorrect time management and callback for AVAudioPlayerNode

I have a serious issue with the new audio engine in iOS8. I have an application, which is built with AVAudioPlayer and I am trying to figure out a way to migrate to the new architecture, however I bumped into the following problem (which I'm sure you would agree, is a serious and basic obstacle):
My header file:
AVAudioEngine *engine;
AVAudioMixerNode *mainMixer;
AVAudioPlayerNode *player;
My m file (inside the viewDidLoad):
engine = [[AVAudioEngine alloc] init];
player = [[AVAudioPlayerNode alloc] init];
[engine attachNode:player];
NSURL *fileUrl = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:#"test" ofType:#"mp3"]];
AVAudioFile *file = [[AVAudioFile alloc] initForReading:fileUrl error:nil];
NSLog(#"duration: %.2f", file.length / file.fileFormat.sampleRate);
[player scheduleFile:file atTime:nil completionHandler:^{
AVAudioTime *nodeTime = player.lastRenderTime;
AVAudioTime *playerTime = [player playerTimeForNodeTime:nodeTime];
float secs = (float)playerTime.sampleTime / file.fileFormat.sampleRate;
NSLog(#"finished at: %.2f", secs);
}];
mainMixer = [engine mainMixerNode];
[engine connect:player to:mainMixer format:file.processingFormat];
[engine startAndReturnError:nil];
[player play];
The above code initializes the engine and a node, then starts playing back whatever file I'm using. First it prints out the duration of the music file, then, after finishing playback, in the callback function, it prints the current time of the player. These two should be the same or in a worst case scenario, very, very close to each other, but this is not the case, the difference between these two values is very big, e.g.
duration: 148.51
finished at: 147.61
Am I doing something wrong? This should be fairly straight forward, I've tried with different file formats, file lengths, tens of music files, but the difference is always around or just under 1 second.
Update:
As of iOS 11 you can specify the completionCallbackType: AVAudioPlayerNodeCompletionCallbackType
dataConsumed:
A completion handler indicating that the buffer or file data has been consumed by the player.
dataRendered:
The buffer or file data that has been rendered by the player.
dataPlayedBack:
A completion handler indicating that the buffer or file has finished playing.
More info: Documentation
Original:
According to Apple's documentation for scheduleFile:atTime:completionHandler:
It is possible for the completionHandler to be called before rendering
begins or before the file is played completely.

AFNetworking and multiple UIImageViews pulling from same URL

I have an issue where im loading 3, sometimes 4 of the same images using
[imageFile setImageWithURL:[NSURL URLWithString:friendAvatar] placeholderImage:[UIImage imageNamed:#"defaultProfileImage.png"]];
Im trying to see if theres a way to load this into some kind of NSData and use it later on, kind of like how im doing below, but using AFNetworking.
dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^(void)
{
NSURL *url3 = [NSURL URLWithString:friendAvatar];
NSData *data = [NSData dataWithContentsOfURL:url3];
UIImage *img = [[UIImage alloc] initWithData:data];
dispatch_async( dispatch_get_main_queue(), ^(void){
imageFile.image = img;
bgImageFile.image = img;
});
});
Also im not calling the image loads all in the same method, 2 call under the cellForRowAtIndexPath once the users friends list has been populated, then the 3rd gets loaded when i swipe over a cell to show its hidden (under) layer, the 4th repeat image gets called when pressing a button that is showed once the cell has been swiped which leads to a chatroom view between me and that friend.
Hopefully i got to my point on what im trying to acheive. And any help pointing in the right direction is very much appreciated.
Update:
This is my current code, this is what i mean by im pulling the same image several times.
Inside the cellForRowAtIndexPath
[imageFile setImageWithURLRequest:request placeholderImage:[UIImage imageNamed:#"defaultProfileImage.png"]];
[bgImageFile setImageWithURL:[NSURL URLWithString:friendAvatar] placeholderImage:[UIImage imageNamed:#"defaultProfileImage.png"]];
The method bottomDrawerWillAppear that is called contains
UIImageView *drawerBGImg = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,75)];
NSString *friendAvatar = [NSString stringWithFormat:#"%#%#%#", #"http://v9a2a7.com/user_photos/", [MyClass friendID], #".jpg"];
[drawerBGImg setImageWithURL:[NSURL URLWithString:friendAvatar]];
And on a seperate class and seperate view viewMessageViewController
NSString *friendAvatar = [NSString stringWithFormat:#"%#%#%#", #"http://v9a2a7.com/user_photos/", email, #".jpg"];
[bgImage setImageWithURL:[NSURL URLWithString:friendAvatar]];
I have not confirmed that the viewMessageViewsController's forces the image to be pulled from the server, but i know for a fact on the cellForRowAtIndexPath makes 3 requests for the same image which results in using 3X the amount of data usage
Hope this clears things up.
It sounds like you want to cache the image so you don't have to keep loading it. Assuming that's what you mean...
The AFNetworking method [UIImageView -setImageWithURL:placeholderImage:] already caches this image for you. The second time you call it, the image will be loaded from the cache.
The only reason it would get reloaded from the server a second time is if your app receives a low memory warning since the last download. (AFImageCache, an NSCache subclass, will automatically invalidate some or all of the cache.)
It uses the URL as the key, so as long as the URL is identical, the image will only get loaded from the server once.

How update image from URL in OS X app?

i have some problem. So i have code which update song name and picture from php. Song name work and also updated but picture not work, in php file all work but in my project - no. How make update picture from url after 10 sec for example. Thanks.
-(void)viewWillDraw {
NSURL *artistImageURL = [NSURL URLWithString:#"http://site.ru/ParseDataField/kiss.php?image"];
NSImage *artistImage = [[NSImage alloc] initWithContentsOfURL:artistImageURL];
[dj setImage:artistImage];
dispatch_queue_t queue = dispatch_get_global_queue(0,0);
dispatch_async(queue, ^{
NSError* error = nil;
NSString* text = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://site.ru/ParseDataField/kiss.php?artist"]
encoding:NSASCIIStringEncoding
error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
[labelName setStringValue:text];
});
});
}
You should really consider placing this code someplace other than -viewWillDraw. This routine can be called multiple times for the same NSView under some circumstances and, more importantly, you need to call [super viewWillDraw] to make sure that things will actually draw correctly (if anything is drawn in the view itself).
For periodic updates (such as every 10 seconds), you should consider using NSTimer to trigger the retrieval of the next object.
As for the general question of why your image isn't being drawn correctly, you should probably consider putting the image retrieval and drawing code into the same structure as your label retrieval and drawing code. This will get the [dj setImage: artistImage] method call outside of the viewWillDraw chain which is likely causing some difficulty here.

QTKit, capture video for live streaming

I am trying to create an application for the Mac that would create live video streaming. I know about VLC and other solutions, but still.
To that end i am trying to record video from iSight using QTKit, and save it continuously as a series of tiny video files. However, the recording turns out not quite continuous, with gaps between the files.
Basically, I am just setting up a timer, that starts recording to a new file at certain time intervals, thus stopping the old recording. I also tried setting the max recorded length, and using a delegate method ...didFinishRecording... and ...willFinishRecording..., but with the same result (i can't really estimate the difference between the gaps in these cases).
Please, help me, if you know how these things should be done.
Here is my current code:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
QTCaptureSession *session = [[QTCaptureSession alloc] init];
QTCaptureDevice *iSight = [QTCaptureDevice defaultInputDeviceWithMediaType:QTMediaTypeVideo];
[iSight open:nil];
QTCaptureDeviceInput *myInput = [QTCaptureDeviceInput deviceInputWithDevice:iSight];
output = [[QTCaptureMovieFileOutput alloc] init] ; //ivar, QTCaptureFileOutput
[output setDelegate:self];
a = 0; //ivar, int
fileName = #"/Users/dtv/filerecording_"; //ivar, NSString
[session addOutput:output error:nil];
[session addInput:myInput error:nil];
[capview setCaptureSession:session]; //IBOutlet
[session startRunning];
[output setCompressionOptions:[QTCompressionOptions compressionOptionsWithIdentifier:#"QTCompressionOptionsSD480SizeH264Video"] forConnection:[[output connections] objectAtIndex:0]];
[output recordToOutputFileURL:[NSURL fileURLWithPath:[NSString stringWithFormat:#"%#%i.mov", fileName, a]] bufferDestination:QTCaptureFileOutputBufferDestinationOldFile];
NSTimer *tmr = [NSTimer timerWithTimeInterval:5 target:self selector:#selector(getMovieLength:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:tmr forMode:NSDefaultRunLoopMode];
}
&dash; (void) getMovieLength:(NSTimer *) t {
a++;
[output recordToOutputFileURL:[NSURL fileURLWithPath:[NSString stringWithFormat:#"%#%i.mov", fileName, a]] bufferDestination:QTCaptureFileOutputBufferDestinationOldFile];
}
There is a native mechanism to brake the captured movie into pieces. Use
[QTCaptureFileOutput setMaximumRecordedDuration:]
to specify the duration of the piece or
[QTCaptureFileOutput setMaximumRecordedFileSize:]
to specify the file size limit.
When the limit is reached the delegate method will be called:
[QTCaptureFileOutput_Delegate captureOutput: shouldChangeOutputFileAtURL: forConnections: dueToError:]
In the this method you can set the new file name:
[QTCaptureFileOutput recordToOutputFileURL:]
This will allow you to cut the pieces of the recorded movie pretty precisely.
Note, that [QTCaptureFileOutput_Delegate captureOutput: didFinishRecordingToOutputFileAtURL: forConnections: dueToError:] will be called a bit later after the recoding into the file has been actually finished. If you use this method to set the new file you will have gaps in the final video. It does not mean you do not need to use this method though. This method will indicated when the piece of the movie is ready to be used.
If you need even more precise cutting you can use
[QTCaptureFileOutput captureOutput: didOutputSampleBuffer: fromConnection:]
to specify the exact movie frame when to start recording into a new piece. However, you will need more specific knowledge to work with the method.

Placing an NSTimer in a separate thread

Note: It's probably worth scrolling down to read my edit.
I'm trying to setup an NSTimer in a separate thread so that it continues to fire when users interact with the UI of my application. This seems to work, but Leaks reports a number of issues - and I believe I've narrowed it down to my timer code.
Currently what's happening is that updateTimer tries to access an NSArrayController (timersController) which is bound to an NSTableView in my applications interface. From there, I grab the first selected row and alter its timeSpent column. Note: the contents of timersController is a collection of managed objects generated via Core Data.
From reading around, I believe what I should be trying to do is execute the updateTimer function on the main thread, rather than in my timers secondary thread.
I'm posting here in the hopes that someone with more experience can tell me if that's the only thing I'm doing wrong. Having read Apple's documentation on Threading, I've found it an overwhelmingly large subject area.
NSThread *timerThread = [[[NSThread alloc] initWithTarget:self selector:#selector(startTimerThread) object:nil] autorelease];
[timerThread start];
-(void)startTimerThread
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
activeTimer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateTimer:) userInfo:nil repeats:YES] retain];
[runLoop run];
[pool release];
}
-(void)updateTimer:(NSTimer *)timer
{
NSArray *selectedTimers = [timersController selectedObjects];
id selectedTimer = [selectedTimers objectAtIndex:0];
NSNumber *currentTimeSpent = [selectedTimer timeSpent];
[selectedTimer setValue:[NSNumber numberWithInt:[currentTimeSpent intValue]+1] forKey:#"timeSpent"];
}
-(void)stopTimer
{
[activeTimer invalidate];
[activeTimer release];
}
UPDATE
I'm still totally lost with regards to this leak. I know I'm obviously doing something wrong, but I've stripped my application down to its bare bones and still can't seem to find it. For simplicities sake, I've uploaded my applications controller code to: a small pastebin. Note that I've now removed the timer thread code and instead opted to run the timer in a separate runloop (as suggested here).
If I set the Leaks Call Tree to hide both Missing Symbols and System Libraries, I'm shown the following output:
EDIT: Links to screenshots broken and therefor removed.
If the only reason you are spawning a new thread is to allow your timer to run while the user is interacting with the UI you can just add it in different runloop modes:
NSTimer *uiTimer = [NSTimer timerWithTimeInterval:(1.0 / 5.0) target:self selector:#selector(uiTimerFired:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:uiTimer forMode:NSRunLoopCommonModes];
As an addendum to this answer it is now possible to schedule timers using Grand Central Dispatch and blocks:
// Update the UI 5 times per second on the main queue
// Keep a strong reference to _timer in ARC
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, (1.0 / 5.0) * NSEC_PER_SEC, 0.25 * NSEC_PER_SEC);
dispatch_source_set_event_handler(_timer, ^{
// Perform a periodic action
});
// Start the timer
dispatch_resume(_timer);
Later when the timer is no longer needed:
dispatch_source_cancel(_timer);

Resources