-
轉載請註明出處:ARKit從入門到精通(6)-ARSession介紹
-
ARSession是一個連接底層與AR視圖之間的橋樑,其實ARSCNView內部所有的代理方法都是由ARSession來提供的
-
ARSession與ARScnView之間的關係看起來是這樣的:
-
-
ARSession獲取相機位置數據主要有兩種方式
- 第一種:push。 實時不斷的獲取相機位置,由ARSession主動告知用戶。通過實現ARSession的代理
- (void)session:(ARSession *)session didUpdateFrame:(ARFrame *)frame
來獲取 - 第二種:pull。 用戶想要時,主動去獲取。ARSession的屬性
currentFrame
來獲取
- 第一種:push。 實時不斷的獲取相機位置,由ARSession主動告知用戶。通過實現ARSession的代理
-
- API介紹
@interface ARSession : NSObject
/**
代理
*/
@property (nonatomic, weak) id <ARSessionDelegate> delegate;
/**
指定代理執行的線程(主線程不會有延遲,子線程會有延遲),不指定的話默認主線程
*/
@property (nonatomic, strong, nullable) dispatch_queue_t delegateQueue;
/**
相機當前的位置(是由會話追蹤配置計算出來的)
*/
@property (nonatomic, copy, nullable, readonly) ARFrame *currentFrame;
/**
會話追蹤配置
*/
@property (nonatomic, copy, nullable, readonly) ARSessionConfiguration *configuration;
/**
運行會話(這行代碼就是開啓AR的關鍵所在)
*/
- (void)runWithConfiguration:(ARSessionConfiguration *)configuration NS_SWIFT_UNAVAILABLE("Use run(_:options:)");
/**
運行會話,只是多了一個參數ARSessionRunOptions:作用就是會話斷開重連時的行爲。ARSessionRunOptionResetTracking:表示充值追蹤 ARSessionRunOptionRemoveExistingAnchors:移除現有錨點
*/
- (void)runWithConfiguration:(ARSessionConfiguration *)configuration options:(ARSessionRunOptions)options NS_SWIFT_NAME(run(_:options:));
/**
暫停會話
*/
- (void)pause;
/**
添加錨點
*/
- (void)addAnchor:(ARAnchor *)anchor NS_SWIFT_NAME(add(anchor:));
/**
移除錨點
*/
- (void)removeAnchor:(ARAnchor *)anchor NS_SWIFT_NAME(remove(anchor:));
@end
//session代理分類兩部分,一個是觀察者(KVO) 一個是委託者(代理)
#pragma mark - ARSessionObserver
//session KVO觀察者
@protocol ARSessionObserver <NSObject>
@optional
/**
session失敗
*/
- (void)session:(ARSession *)session didFailWithError:(NSError *)error;
/**
相機改變追蹤狀態
*/
- (void)session:(ARSession *)session cameraDidChangeTrackingState:(ARCamera *)camera;
/**
session意外斷開(如果開啓ARSession之後,APP退到後臺就有可能導致會話斷開)
*/
- (void)sessionWasInterrupted:(ARSession *)session;
/**
session會話斷開恢復(短時間退到後臺再進入APP會自動恢復)
*/
- (void)sessionInterruptionEnded:(ARSession *)session;
@end
#pragma mark - ARSessionDelegate
@protocol ARSessionDelegate <ARSessionObserver>
@optional
/**
相機當前狀態(ARFrame:空間位置,圖像幀等)更新
*/
- (void)session:(ARSession *)session didUpdateFrame:(ARFrame *)frame;
/**
添加錨點
*/
- (void)session:(ARSession *)session didAddAnchors:(NSArray<ARAnchor*>*)anchors;
/**
刷新錨點
*/
- (void)session:(ARSession *)session didUpdateAnchors:(NSArray<ARAnchor*>*)anchors;
/**
移除錨點
*/
- (void)session:(ARSession *)session didRemoveAnchors:(NSArray<ARAnchor*>*)anchors;
@end