Download presentation
Presentation is loading. Please wait.
1
感測器
2
Connecting to the Net
3
Foundation Framework Many classes in the Foundation framework support initialization of some form via a URL NSString NSArray NSDictionary + (id)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error; + (id)arrayWithContentsOfURL:(NSURL *)url; + (id)dictionaryWithContentsOfURL:(NSURL *)url;
4
練習 URL: http://192.168.11.15/zipcode.php?zip=郵遞 區號,可查詢傳入郵遞區號的縣市鄉鎮 回傳資料
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" " <plist version="1.0"> <dict> <key>county</key><string>台北市</string> <key>city</key><string>信義區</string> </dict> </plist> 100,103~106,108,110
6
記得要將searchBar的delegate連接到此ViewCrotoller
#import "IHViewController.h" #define @implementation IHViewController - (void)viewDidLoad{ [super viewDidLoad]; } - (void)didReceiveMemoryWarning{ [super didReceiveMemoryWarning]; -(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{ NSString *zip = searchBar.text; NSString *urlStr = [NSString webUrl, zip]; NSURL *url = [NSURL URLWithString:urlStr]; NSDictionary *results = [NSDictionary dictionaryWithContentsOfURL:url]; self.county.text =[results ; self.city.text = [results ; @end 記得要將searchBar的delegate連接到此ViewCrotoller
7
Network IO blocking What happens if the network request takes a long time to fulfill? The UI becomes totally unresponsive The network IO blocking is being done in the UI thread How does the user know the app is doing network IO and not just hung trying to perform some local operation?
8
Perform Blocking IO in Background
You should not perform any potentially long- running IO in the main thread — it will halt the UI Instead you should run these in a different thread that doesn’t cause the UI to block Couple of ways to achieve this... Traditional threads Asynchronous functions Operation queues
9
NSThread Class + (void)detachNewThreadSelector: (SEL)aSelector toTarget:(id)aTarget withObject: (id)anArgument 自動執行 - (id)initWithTarget:(id)target selector: (SEL)selector object:(id)argument 需呼叫start selector: 執行緒入口點方法,只能有一個參數,無回傳 值 argument:傳入selector方法的參數 - (void)start
10
NSThread *thread1=[[NSThread alloc]initWithTarget:self
object:nil]; [thread1 start]; -(void)doInThread { for(int i=0;i<100;i++) %d",i); }
11
NSOperationQueue 在iOS中,可以建立多個不同步操作的執行緒, 可在目前執行緒中同時啟動多個操作
+ (id)mainQueue Returns the operation queue associated with the main thread - (NSInteger)maxConcurrentOperationCount - (NSArray *)operations - (NSUInteger)operationCount
12
NSOperationQueue - (void)addOperation:(NSOperation *)op;
- (void)addOperations:(NSArray *)ops waitUntilFinished:(BOOL)wait wait YES:目前執行緒會被 blocked直到指定的操作執行完 NO:將操作放入佇列中後,馬上返回 - (void)addOperationWithBlock:(void (^) (void))block
13
NSOperationQueue - (void)cancelAllOperations
- (void)waitUntilAllOperationsAreFinished Block目前執行緒直到佇列中的操作都執行完
14
NSOperation NSOperation:是一個抽象類別,用來包裝一個 任務工作 實體類別有 可調整任務工作的排程優先權
可設定一個 block工作 實體類別有 NSInvocationOperation NSBlockOperation
15
NSInvocationOperation
- (id)initWithTarget:(id)target selector: (SEL)sel object:(id)arg NSInvocationOperation *invocation=[[NSInvocationOperation alloc]initWithTarget:self object:nil]; NSOperationQueue *queue=[[NSOperationQueue alloc]init]; [queue addOperation:invocation]; -(void)doInThread { for(int i=0;i<100;i++) %d",i); }
16
Declaring and Using a Block
use the ^ operator to declare a block variable and to indicate the beginning of a block literal. The body of the block itself is contained within {} int multiplier = 7; int (^myBlock)(int) = ^(int num) { return num * multiplier; };
17
Declaring and Using a Block
18
Declaring and Using a Block
Block可以使用與Block定義相同範圍的變數 定義了一個block變數就可以像方法一樣使用 int multiplier = 7; int (^myBlock)(int) = ^(int num) { return num * multiplier; }; printf("%d", myBlock(3)); // prints "21"
19
int multiplier = 7; int (^myBlock)(int) = ^(int num) { return num * multiplier; }; myBlock(3)); multiplier = 8; 21 21 __block int multiplier = 7; int (^myBlock)(int) = ^(int num) { return num * multiplier; }; myBlock(3)); multiplier = 8; 21 24
20
int multiplier = 7; int (^myBlock)(int) = ^(int num) { multiplier++; return num * multiplier; }; %d multiplier:%d", multiplier, myBlock(3),multiplier); __block multiplier:7 24 multiplier:8
21
Declaring and Using a Block
也可以不需要宣告一個block變數,直接在參數 中撰寫一個block區塊 如:UIViewController的方法 (void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion [self presentViewController:viewController animated:YES completion:^{...} ];
22
NSBlockOperation + (id)blockOperationWithBlock:(void (^)(void))block;
- (void)addExecutionBlock:(void (^)(void))block; 加入任務工作block - (void)setCompletionBlock:(void (^)(void))block 設定操作完成時執行的程式block
23
NSObject Class - (void)performSelectorOnMainThread: (SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait 將此物件要執行的方法放到主執行緒中執行
24
- (void)performSelectorOnMainThread: (SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait
要放到主執行緒中執行的方法 此方法不能有回傳直,最多只能有一個參數 arg: 要傳遞到方法中的參數 若方法無需參數,則此參數設為 nil wait: 設定目前執行緒是否需要等待主執行緒執行完該方法
25
Notifying the User of Network IO
設定網路存取指示 取得UIApplication物件 設定網路存取指示是否可見 @property(nonatomic,getter=isNetworkActivityIn dicatorVisible) BOOL networkActivityIndicatorVisible; + (UIApplication *)sharedApplication;
26
改良上一個練習 #import <UIKit/UIKit.h>
@interface IHViewController : UIViewController<UISearchBarDelegate> @property (weak, nonatomic) IBOutlet UILabel *county; @property (weak, nonatomic) IBOutlet UILabel *city; @property (strong, nonatomic) NSOperationQueue *queue; @end
27
UIApplication *app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES; NSString *zip = searchBar.text; NSString *urlStr=[NSString webUrl, zip]; NSURL *url = [NSURL URLWithString:urlStr]; NSBlockOperation *lookupOp = [NSBlockOperation blockOperationWithBlock:^ { NSDictionary *results = [NSDictionary dictionaryWithContentsOfURL:url]; [self.county withObject: [results waitUntilDone:YES]; [self.city withObject:[results waitUntilDone:YES]; } ]; [lookupOp setCompletionBlock:^{ app.networkActivityIndicatorVisible = NO; }]; if (!self.queue) { self.queue = [[NSOperationQueue alloc] init]; [self.queue addOperation:lookupOp];
28
接近感測器
29
UIDevice 接近感測器相關屬性 提供設備相關資訊 + (UIDevice *)currentDevice
BOOL proximityMonitoringEnabled 設定是否監測物體靠近 預設是NO. BOOL proximityState 是否有物體靠近
30
UIDevice Notifications UIDeviceProximityStateDidChangeNotification
31
Notification 採用廣播方式,將發送出去的訊息廣播給註冊 過的觀測者,觀測者對訊息進行處理
NSNotificationCenter 訊息中心,每一個Process都會有一個此物件 + (id)defaultCenter 回傳預設的NSNotificationCenter物件 NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
32
Notification - (void)addObserver:(id)notificationObserver
selector:(SEL)notificationSelector name:(NSString *)notificationName object:(id)notificationSender - (void)removeObserver: (id)notificationObserver - (void)removeObserver:(id)notificationObserver
33
接近感測器—練習 啟用接近感測器 訂閱接近感測器變化通知 取得接近狀態
[UIDevice currentDevice].proximityMonitoringEnabled=YES; 訂閱接近感測器變化通知 取得接近狀態 if ([UIDevice currentDevice].proximityMonitoringEnabled) { [[NSNotificationCenter defaultCenter] addObserver:self name:UIDeviceProximityStateDidChangeNotification object:nil]; } -(void)handleProximityChange:(NSNotification *) notification{ State: %d",[UIDevice currentDevice].proximityState); }
34
Motion sensing
35
Motion sensing 主要感測器: 加速度計、陀螺儀、磁力計 取得感測器值主要類別CMMotionManager
使用alloc/init來建立物件,但每個應用程式只允許建 立一個此物件
36
Motion sensing 使用步驟 ... or ... 檢查硬體是否可用
開始取樣,並詢問 motion manager取得最新的感測值 ... or ... 設定感測值回報頻率 註冊一個block,每當一個取樣值取得時,會執行此 block
37
CMMotionManager Class
檢查感測器硬體是否可用 @property (readonly) BOOL {accelerometer,gyro,deviceMotion,magnetometer}Availa ble; deviceMotion是加速度計和陀螺儀兩者結合 啟動硬體開始收集資料 若要開始polling感測值,只需要呼叫啟動方法 - (void)start{Accelerometer,Gyro,DeviceMotion,Magnetom eter}Updates;
38
CMMotionManager Class
停止感測資料 (void)stop{Accelerometer,Gyro,DeviceMotion,Magnetometer}Upda tes; 判斷目前感測器是否active @property (readonly) BOOL {accelerometer,gyro,deviceMotion,magnetometer}Active;
39
Polling data 取得加速度感測資料 CMAccelerometerData物件有以下屬性
@property (readonly) CMAccelerometerData *accelerometerData; CMAccelerometerData物件有以下屬性 @property (readonly) CMAcceleration acceleration; 此加速度包含重力加速度 typedef struct { double x; double y; double z; } CMAcceleration;
40
Polling data 取得陀螺儀感測資料 @property (readonly) CMGyroData *gyroData;
@property (readonly) CMRotationRate rotationRate; 旋轉速率正負值依據右手定則 此值會有偏差 typedef struct { double x; double y; double z; } CMRotationRate
41
Polling data 取得磁力計感測資料
@property(readonly) CMMagnetometerData *magnetometerData CMMagnetometerData物件有以下屬性 @property(readonly, nonatomic) CMMagneticField magneticField typedef struct { double x; double y; double z; } CMMagneticField;
42
Polling data 取得移動資料 @property (readonly) CMDeviceMotion *deviceMotion;
若裝置有此兩種感測器,可以有更佳的感測結果
43
CMDeviceMotion 加速度資訊 @property (readonly) CMAcceleration gravity;
@property (readonly) CMAcceleration userAcceleration; 不含重力加速度
44
CMDeviceMotion 磁力資訊 @property(readonly, nonatomic) CMCalibratedMagneticField magneticField 去除地球磁場和裝置誤差 typedef struct { double x; double y; double z; } CMMagneticField; typedef struct { CMMagneticField field; CMMagneticFieldCalibrationAccuracy accuracy; } CMCalibratedMagneticField; typedef enum { CMMagneticFieldCalibrationAccuracyUncalibrated = -1,//未校準 CMMagneticFieldCalibrationAccuracyLow, CMMagneticFieldCalibrationAccuracyMedium, CMMagneticFieldCalibrationAccuracyHigh } CMMagneticFieldCalibrationAccuracy;
45
CMDeviceMotion 旋轉資訊 @property CMRotationRate rotationRate;
Contains a measurement of gyroscope data whose bias has been removed . @property CMAttitude *attitude; 裝置在3-D空間中的朝向(姿勢) @interface CMAttitude : NSObject // 單位為徑度(弧度) @property (readonly) double roll; // 以Y軸為軸心旋轉方向的弧度 @property (readonly) double pitch; //以x軸為軸心 @property (readonly) double yaw; //以z軸為軸心 @end
46
Core Motion 設定感側值回報頻率 @property NSTimeInterval accelerometerUpdateInterval; @property NSTimeInterval gyroUpdateInterval; @property NSTimeInterval deviceMotionUpdateInterval; @property NSTimeInterval magnetometerUpdateInterval;
47
Core Motion 註冊接收加速度資料回報的區塊
(void)startAccelerometerUpdatesToQueue: (NSOperationQueue *)queue withHandler: (CMAccelerometerHandler)handler; CMAccelerometerHandler typedef void (^CMAccelerationHandler) (CMAccelerometerData *data, NSError *error);
48
Core Motion 註冊接收旋轉資料回報的區塊
(void) startGyroUpdatesToQueue: (NSOperationQueue *) queue withHandler: (CMGyroHandler)handler; CMGyroHandler typedef void (^CMGyroHandler)(CMGyroData *data, NSError *error);
49
Core Motion 註冊接收加速度和旋轉資料回報的區塊
(void) startDeviceMotionUpdatesToQueue: (NSOperationQueue *) queue withHandler: (CMDeviceMotionHandler)handler; CMDeviceMotionHandler typedef void (^CMDeviceMotionHandler) (CMDeviceMotion *motion, NSError *error);
50
Core Motion 註冊接收磁力資料回報的區塊
(void)startMagnetometerUpdatesToQueue:(NSOperationQu eue *)queue withHandler:(CMMagnetometerHandler)handler CMMagnetometerHandler typedef void (^CMMagnetometerHandler)(CMMagnetometerData *magnetometerData, NSError *error);
51
練習 讀出手機x, y, z軸之加速度,與使用者在三軸上 之移動加速度。 Add CoreMotion.framework
52
#import <UIKit/UIKit.h>
#import <CoreMotion/CoreMotion.h> @interface weatherViewController : UIViewController @property(nonatomic,strong)CMMotionManager * motionMager; @end self.motionMager = [[CMMotionManager alloc] init]; NSOperationQueue *queue = [ [NSOperationQueue alloc] init]; if (self.motionMager.accelerometerAvailable) { self.motionMager.accelerometerUpdateInterval = 5.0; [self.motionMager startAccelerometerUpdatesToQueue:queue withHandler: ^(CMAccelerometerData *accelerometerData, NSError *error) { } ];
53
練習 畫面中顯示一個圖片,圖片會隨加速度計頃斜移 動
Similar presentations