Skip to content

Instantly share code, notes, and snippets.

@akhenakh
Created November 2, 2018 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akhenakh/af53e03f1c464534216a1d74802a4bb9 to your computer and use it in GitHub Desktop.
Save akhenakh/af53e03f1c464534216a1d74802a4bb9 to your computer and use it in GitHub Desktop.
query a static image camera and animate it
//
// MJPEGViewController.m
// iMocs
//
// Created by akh on 2018-10-29.
// Copyright ? 2018 akh. All rights reserved.
//
#import "MJPEGViewController.h"
@interface MJPEGViewController ()
- (IBAction)reloadTouched:(id)sender;
@property (weak, nonatomic) IBOutlet UIView *connectedView;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic, strong) dispatch_source_t timerSource;
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation MJPEGViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
config.timeoutIntervalForResource = 10;
config.timeoutIntervalForRequest = 0.3;
self.session = [NSURLSession sessionWithConfiguration:config];
}
- (void) fetchOne {
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.12.1:8080/?action=snapshot"]] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error != nil) {
NSLog(@"error dl image %@", [error localizedDescription]);
dispatch_async(dispatch_get_main_queue(), ^{
self.connectedView.backgroundColor = [UIColor redColor];
});
}
UIImage *downloadedImage = [UIImage imageWithData:data];
if (downloadedImage != nil) {
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = downloadedImage;
self.connectedView.backgroundColor = [UIColor greenColor];
});
}
dispatch_semaphore_signal(sem);
}];
[dataTask resume];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
}
- (void) play {
[self.timer invalidate];
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.125
target:self
selector:@selector(fetchOne)
userInfo:nil
repeats:YES];
}
- (void) stop {
self.connectedView.backgroundColor = [UIColor redColor];
[self.timer invalidate];
}
- (void) viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self play];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[self stop];
}
- (IBAction)reloadTouched:(id)sender {
[self stop];
[self play];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment