Saturday, December 17, 2016

[iOS SDK] AVCaptureSession on iOS10, Xcode 8, and swift3

I used AVCaptureSession about 3 years ago to take a user profile picture in the app.
But I found that there are some changes for a while.

So, here is very simple example for using AVCaptureSession.

class CameraViewController: UIViewController {
    
    @IBOutlet weak var layerView : UIView!
    var previewLayer : AVCaptureVideoPreviewLayer!
    var stillImageOutput : AVCapturePhotoOutput = AVCapturePhotoOutput();

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        initCameraOverlay();
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

    func initCameraOverlay() {
        let session = AVCaptureSession();
        session.sessionPreset = AVCaptureSessionPresetPhoto;
        
        previewLayer = AVCaptureVideoPreviewLayer(session: session);
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        previewLayer.frame = layerView.bounds;
        layerView.layer.addSublayer(previewLayer);
        
        layerView.layer.masksToBounds = true;
        
        let descoverySession = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera , .builtInDualCamera], mediaType: AVMediaTypeVideo, position: .unspecified);
        if let devices = descoverySession?.devices {
            for device in devices {
                if (device.position == .back) {
                    do {
                        let input = try AVCaptureDeviceInput(device: device)
                        if session.canAddInput(input) {
                            session.addInput(input)
                        }
                    }
                    catch {
                        
                    }
                }
                if (device.position == .front) {
                    // Do something
                }
            }
        }
        
        if session.canAddOutput(self.stillImageOutput) {
            session.addOutput(stillImageOutput);
        }
        
        session.startRunning();
    }

}

Monday, December 5, 2016

[iOS SDK] Core Data with Xcode8, iOS10 and Swift3

[iOS SDK] Core Data with Xcode8, iOS10 and Swift3


There are lots of posting and blog about core data. But there were many changes in core data in Xcode 8, iOS 10 and Swift 3. Actually most postings were not useful for me, so I tried many way to find working codes.


  • Data Model
    In this example, the model is very simple. Only one Entity with some attributes and there is no relationships.




  • Fetch LibraryItem Entity
    func getContext() -> NSManagedObjectContext {
        return self.persistentContainer.viewContext;
    }
    func fetchLibraryList() -> [LibraryItem]? {
        // context = self.persistentContainer.viewContext
        let context = getContext();
            
        let fetchRequest : NSFetchRequest<NSFetchRequestResult> = LibraryItem.fetchRequest();
        let entityDescription = NSEntityDescription.entity(forEntityName: "LibraryItem", in: context);
        fetchRequest.entity = entityDescription;
        fetchRequest.predicate = NSPredicate(format: "checkin_date = nil");
            
        var fetchedObjects : [LibraryItem]? = nil;
        do {
            fetchedObjects = try context.fetch(fetchRequest) as? [LibraryItem];
        }
        catch {
            print("Error in fetching data from core data");
        }
            
        return fetchedObjects;
    }

Thursday, June 9, 2016

UI Dynamics

@interface ViewController ()

@property (strong, nonatomic) UIDynamicAnimator* animator;
@property (nonatomic) UIOffset offset;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIPanGestureRecognizer* pg = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(actionPanGesture:)];
    [self.imageView addGestureRecognizer:pg];
    self.imageView.userInteractionEnabled = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) actionPanGesture:(UIPanGestureRecognizer*)pg {
    CGPoint pInView = [pg locationInView:self.view];
    CGPoint pInSubView = [pg locationInView:pg.view];
    CGPoint center = CGPointMake(pg.view.bounds.size.width/2., pg.view.bounds.size.height/2.);
 
    CGPoint v = [pg velocityInView:self.view];
 
    if (pg.state == UIGestureRecognizerStateBegan) {
        self.offset = UIOffsetMake(pInSubView.x - center.x, pInSubView.y - center.y);
        NSLog(@"OffsetX: %f, OffsetY: %f", self.offset.horizontal, self.offset.vertical);
    }
    else if (pg.state == UIGestureRecognizerStateEnded) {
        self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
     
        NSLog(@"PushVX: %f, PushVY: %f", v.x, v.y);
        UIPushBehavior* push = [[UIPushBehavior alloc] initWithItems:@[pg.view] mode:UIPushBehaviorModeInstantaneous];
        [push setPushDirection:CGVectorMake(v.x/10.0, v.y/10.0)];
        [self.animator addBehavior:push];
     
        UIGravityBehavior* gravity = [[UIGravityBehavior alloc] initWithItems:@[pg.view]];
        [self.animator addBehavior:gravity];
    }
    else {
        if (self.animator) {
            self.attachBehavior.anchorPoint = pInView;
            return;
        }
        else {
            self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
        }
        UIGravityBehavior* gravity = [[UIGravityBehavior alloc] initWithItems:@[pg.view]];
        [self.animator addBehavior:gravity];
     
        UIAttachmentBehavior *attachment;
        attachment = [[UIAttachmentBehavior alloc] initWithItem:pg.view offsetFromCenter:self.offset attachedToAnchor:pInView];
        [attachment setLength:0];
        [attachment setFrequency:0];
        [attachment setDamping:5];
        [self.animator addBehavior:attachment];
     
    }
}
@end