網頁

顯示具有 Objective C 標籤的文章。 顯示所有文章
顯示具有 Objective C 標籤的文章。 顯示所有文章

2014年4月2日 星期三

【Objc】將圖片轉為tiff存檔

【環境:xCode 5 , arc】
宣告:
名稱:
說明:將取得的圖片轉為tiff格式,並存起來。


 
NSString *myPath = [[NSBundle mainBundle] pathForResource:@"IMG_2733" ofType:@"JPG"];
    NSURL *myURL = [NSURL fileURLWithPath:myPath];
    CGImageSourceRef mySourceRef = CGImageSourceCreateWithURL((CFURLRef)myURL, NULL);
    NSDictionary *myMetadata = (NSDictionary *) CGImageSourceCopyPropertiesAtIndex(mySourceRef,0,NULL);
    NSDictionary *exifDic = [myMetadata objectForKey:(NSString *)kCGImagePropertyExifDictionary];
    NSDictionary *tiffDic = [myMetadata objectForKey:(NSString *)kCGImagePropertyTIFFDictionary];
    NSLog(@"exifDic properties: %@", myMetadata); //all data
    float rawShutterSpeed = [[exifDic objectForKey:(NSString *)kCGImagePropertyExifExposureTime] floatValue];
    int decShutterSpeed = (1 / rawShutterSpeed);
    NSLog(@"Camera %@",[tiffDic objectForKey:(NSString *)kCGImagePropertyTIFFModel]);
    NSLog(@"Focal Length %@mm",[exifDic objectForKey:(NSString *)kCGImagePropertyExifFocalLength]);
    NSLog(@"Shutter Speed %@", [NSString stringWithFormat:@"1/%d", decShutterSpeed]);
    NSLog(@"Aperture f/%@",[exifDic objectForKey:(NSString *)kCGImagePropertyExifFNumber]);
    NSNumber *ExifISOSpeed  = [[exifDic objectForKey:(NSString*)kCGImagePropertyExifISOSpeedRatings] objectAtIndex:0];
    NSLog(@"ISO %i",[ExifISOSpeed integerValue]);
    NSLog(@"Taken %@",[exifDic objectForKey:(NSString*)kCGImagePropertyExifDateTimeDigitized]); 

As always , if you have any question , feel free to contact me.
有任何問題,請聯絡我

歡迎轉載,請註明出處,感謝。

2014年3月25日 星期二

【iOS】針對某view進行固定方向的旋轉

【環境:xCode5.1 ios6 ios7】

xcode支持的旋轉設定如圖:


在旋轉的方向上,有多種不同的處理方法
1.
可以從application中,監聽哪些viewcontroller正在處理
若滿足某些條件
則進行device上的旋轉

2.對於從單一uviewController上,也可執行如圖,進行旋轉
可以在viewController中,看到此類地宣告。


As always , if you have any question , feel free to contact me.
有任何問題,請聯絡我

歡迎轉載,請註明出處,感謝。

2014年3月14日 星期五

【ios】status bar hidden

【環境:ios6,7】


ios6只需要以下
 
[[UIApplication sharedApplication] setStatusBarHidden:YES]; 

ios7
 
[[UIApplication sharedApplication] setStatusBarHidden:YES]; 
且在plist中設定View controller-based status bar appearance,如圖:





As always , if you have any question , feel free to contact me.
有任何問題,請聯絡我

歡迎轉載,請註明出處,感謝。

2014年3月12日 星期三

【iOS】Cannot install applications because the certificate is not valid

【環境:OTA】

最近重新架設OTA,發生了如圖,的慘狀
一開始我還以為我哪個xcode中的憑證弄錯,重新搞了好久,畢竟以前也沒碰過這個問題
稍微survey一下,原來ios7以上的版本,必須透過安裝server ssl憑證,才可以下載。

所以我回到ios6以下的幾種,果然可以正常安裝
且利用https,在ios6以下並沒辦法安裝

基本上,只需將以下改掉即可
itms-services://?action=download-manifest&url=https://yourdomain.com/manifest.plist
plist中無需更改,聽說是因為apple更改了manifest.plist的權限,只能用https授權過的ssl才可下載安裝,故若你的domain name要可使用OTA的服務,就請去申請安裝ssl憑證吧....
這點我也在try.....

所以....自己在server建立的自我憑證...這是不夠的
https://twitter.com/renderplace/status/426754821044338689
會發生如下圖:



而聽說透過dropbox的免費網頁服務,可以作為暫時之計。

使用方法:(其實只需將plist放至dropbox即可,只是我想都放在一起)
1.將你的plist放至dropbox。
2.對ipa按右鍵,取得分享連結,像此:www.dropbox.com/y/20i6qogfvim7tcy/xxx.ipa
3.將www.dropbox.com改為dl.dropboxusercontent.com
3.開啟你的plist,更改下載的位置如上,也可順便用https傳輸。
4.上傳plist,並取得你plist的分享link,像:www.dropbox.com/c/20i6qogfvim7tcy/xxx.plist
5.將www.dropbox.com改為dl.dropboxusercontent.com
6.回itms-services://?action=download-manifest&url=https://dl.dropboxusercontent.com/a/20i6qogfvim7tcy/xxx.plist


聽說許多國外的開發者,針對這點,有所不滿,畢竟apple每次動這些東西似乎都不會特別提醒...畢竟我也意外被打鎗許多次....

而我也試圖去developer center尋找相關文擋,似乎OTA的部分dis,已經被移除。

下次來寫安裝ssl的流程。



As always , if you have any question , feel free to contact me.
有任何問題,請聯絡我

歡迎轉載,請註明出處,感謝。

2012年7月11日 星期三

app溝通其他外部程式(一)

【環境:xCode4.3.2 , ios5.1 , USE ARC】
參考來源:Communicating with Other Apps


說明:
透過NSURL和UIApplicetion的功能,可以呼叫外部的應用程式。
其中todolist為URL Scheme,是讓應用程式間,彼此知道對方代號的名稱


Note: If more than one third-party app registers to handle the same URL scheme, there is currently no process for determining which app will be given that scheme.
這是Guide中特別標示的一段,表示若多個app均用相同的URL scheme,則目前無法判斷。
有趣的是,國外網站有做一個搜尋目前已經使用過的scheme,目的就是為了盡量避免使用相同的scheme,並且幫助他們建立數據庫:Zwapp


關於URL scheme的介紹,可參考:ios URL Scheme Reference


//使用下方的語法,就可以透過你的app去呼叫外部的應用程式,但前提是必須取得外部應用程式的URL Scheme,才可以呼叫得到。 
NSURL *myURL = [NSURL URLWithString:@"todolist:"];
//『todolist』就是外部app的URL Scheme
[[UIApplication sharedApplication] openURL:myURL];

至於如何呼叫外部app後,做一些事情後,再返回原本的app?


若要帶一些參數呢??

<解析回傳的URL使用方式請參考:NSURL根據RFC 1808下的解析方式>


若想要返回dic的資料呢??


ios提供給我們一個很好的方法,就請參考下一篇文章:app溝通其他外部程式(二)


ps:
要注意的有:從外部app返回後,是返回最後app關到背景的頁面,無法指定跳到任意頁面。
除非動一點小手腳,這邊可以參考UIApplicationDelegate Protocol Reference有興趣的,可以參考,這邊就不多做討論。

As always , if you have any question , feel free to contact me.
有任何問題,請聯絡我

歡迎轉載,請註明出處,感謝。

2012年7月9日 星期一

ARC專案中,針對單一檔案『取消arc的使用』

【環境:xCode4.3.2 , ios5.1 , USE ARC】
說明:
因為ios版本更新速度,舊的sdk等等,本來就不是用ARC去編寫,這樣讓使用者會有很多困擾,所以開發者中心亦提供此種方法,讓使用者可以在ARC的專案環境下,同時使用非使用ARC的SDK,主要利用 -fno-objc-arc 指令的使用
路徑位置:Targets -> Build Phases -> Compile Sources. 




As always , if you have any question , feel free to contact me.
有任何問題,請聯絡我

歡迎轉載,請註明出處,感謝。

2012年7月2日 星期一

File Management(ㄧ)目錄清單位置&list

【環境:xCode4.3.2 , ios5.1 , USE ARC】
說明:

首先要搞清楚 simulator 的 app 資料存放的位置
基本上裡面都會有四個檔案
  1. 一個自己命名的app。
  2. Documents
  3. Library
  4. tmp


<以下範例>
 
    NSLog(@"%@",NSHomeDirectory());//取得目前以此app名稱為根目錄的資料夾位置
    
    NSFileManager *file = [NSFileManager defaultManager];//利用類別方法取得檔案系統的一個預設NSFileManager實體
    //利用這個,可以對根目錄裡的檔案進行操作。
    NSDirectoryEnumerator *dir = [file enumeratorAtPath:NSHomeDirectory()];
    NSString *currPath;
    //依序列出資料夾下的資料有哪些
    while (currPath = [dir nextObject]) {
        NSLog(@"Found : %@",currPath);
    } 

As always , if you have any question , feel free to contact me.
有任何問題,請聯絡我

歡迎轉載,請註明出處,感謝。

2012年6月18日 星期一

Modal View Controller(一)

【環境:xCode4.3.2 , ios5.1 , USE ARC】

說明:基本上,這指的並不是指一般的視圖控制器,而是指一種顯示視圖控制器的方式,當一個視圖控制器,以modal的方式出現時,稱這個視圖控制器是一種modal view controller,這時出現的視圖控制器會暫時中斷目前程式的工作流程,而專注於目前視圖控制器所交辦的工作,modal view controller通常是用來收集使用者的輸入,或者展示某些訊息給使用者。
通常最常看到的就是頁面的切換吧。

  • presentModalViewController: animated:
  • dismissModalViewControllerAnimated:

first畫面
[目前的頁面 presentModalViewController:將要跳轉的頁面 animated:YES];

change 畫面
[self dismissModalViewControllerAnimated:YES];//切換過的畫面,跳回上一層畫面
相關使用方法,請參閱其他資源。

As always , if you have any question , feel free to contact me.
有任何問題,請聯絡我

歡迎轉載,請註明出處,感謝。

視圖控制資源

【環境:xCode4.3.2 , ios5.1 , USE ARC】
說明:
  1. viewWillAppear
  2. viewDidAppear
  3. viewWillDisappear
  4. viewDidDisappear
這四個方法其實是視圖提供的一些狀態更新資訊,當畫面有異動時,他會藉由這四個方法來通知我們,不過不見得所有的程式都需要知道這些更新的狀態。
所以viewWillAppear和viewDidAppear都是適合修改標題的時機。

除了這四種還有
  • viewDidLoad:當試圖完成載入時呼叫,大部份的情況只會被呼叫依次,通常需要額外載入資料都會在這個方法中實作。在前面介紹修改標題的動作移到此處也是相當合適的一個地方。
  • viewDidUnload:當視圖卸載之後呼叫。

視圖除了上述幾種,還包含
-(void) awakeFromNib

當視圖是由xib載入而不是由手動載入時,系統會跳過試圖內建的初始化方式
-(id) initWithFrame:(CGRect)frame;

改由呼叫另一個初始化方法
-(id) initWithCoder:(NSCoder *)decoder
接下來就會呼叫awakeFromNib,因此當我門想要額外對視圖作設定,而這個視圖又剛好是自動由xib檔案載入,awakeFromNib就是一個很適合為視圖進行額外設定的地方。


As always , if you have any question , feel free to contact me.
有任何問題,請聯絡我

歡迎轉載,請註明出處,感謝。

UITableViewController觀念(一)

【環境:xCode4.3.2 , ios5.1 , USE ARC】
名稱:UITableViewDelegate,UITableViewDataSource
說明:
UIViewController:「視圖控制器」
UITableViewController:「表格視圖控制器」,他的基本就是從UIViewController延伸過來,方便開發者容易使用,而不需額外製作多餘的工作,標準物件導向的觀念。

但基本下還是必須瞭解在UIViewController下,如何建立UITableViewController的觀念,因為大多數的使用者包含我,剛開始都會產生一個疑惑,為什麼有些時候必須引用一些protocols<uitableviewdelegate,uitableviewdatasource>,有些時候又不需要,這基本就在於你的基礎框架是什麼,我理解的觀念是這樣。

假如你今天直接用UITableViewController的話,那ios已經幫我們建立了一些基本的設定,好讓我們不需要去煩惱其他東西,只需要去構想內容該怎麼寫,甚至連一些會用到的"實體方法"都幫我們建立好,但一定會有一天需要在其他的框架下去建立UITableViewController的時候,這時我們就必須在.h的檔案下,增加Protocols,<uitableviewdelegate,uitableviewdatasource>,相關的協定(protocols)請去參閱相關資料。

引用相關協定後,才可以使用ios已經幫我們準備好的功能,包含-(NSInteger)numberOfSectionInTableView:(UITableView*)tableView{}.....等等。
<以下範例>
 
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>

@end 

  • UITableViewDelegate:提供表格視圖用來管理、設定表格區段、標題、頁尾等等所需的資訊,同時亦協助管理表格資料的刪除、修改等工作。
  • UITableViewSource:為表格提供顯示的資料。
額外補充
UITableViewController實作了一個叫做UITableViewDataSource的協定。  UITableViewDataSource拆開後可以看到幾個關鍵字。
-UI:表示這個元件是一個UI介面。
-TableView:表示這個元件是表格視圖。
-DataSource:表示這是某個東西的資料來源。
所以整體來說應該是這樣解釋,這個元件的來源是表格視圖的UI介面。
就是要告訴表格視圖的資料來源是什麼,而我們正透過這個協定來告訴表格視圖該顯示什麼資料。

As always , if you have any question , feel free to contact me.
有任何問題,請聯絡我

歡迎轉載,請註明出處,感謝。

2012年6月14日 星期四

NSUserDefaults 取得裝置預設的語言

【環境:xCode4.3.2 , ios5.1 , USE ARC】

說明:有些時候,我們在製做app時,可能必須讀取該手機使用者的目前所使用的語言,去判定該如何進行資料庫的搜尋,或者線上搜尋等等,或者其他的應用。
這是利用NSUserDefaults的特性,抓出目前使用者設備中預設的語言。

<以下範例>
 
    NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
    NSArray* languages = [defs objectForKey:@"AppleLanguages"];
    NSString* preferredLang = [languages objectAtIndex:0];
    NSLog(@"%@",preferredLang);
    
    /*
    for (int i=0; i國際設定->語言->語言列表array...[0][1][2][3][4]
    General -> international -> Language -> language list , array[0][1][2][3][4]
    */ 

As always , if you have any question , feel free to contact me.
有任何問題,請聯絡我

UIDevice抓取目前設備資訊

【環境:xCode4.3.2 , ios5.1】

<以下範例>

主要文件檔案請參考  UIDevice
 
NSLog(@"this : %@",[[UIDevice currentDevice] model]);
//獲取目前使用的設備
NSLog(@"%@",[[UIDevice currentDevice] name]);
// Name of the phone as named by user
NSLog(@"%@",[[UIDevice currentDevice] uniqueIdentifier]);
// A GUID like string
NSLog(@"%@",[[UIDevice currentDevice] systemName]);
// "iPhone OS"
NSLog(@"%@",[[UIDevice currentDevice] systemVersion]);
// "2.2.1"
NSLog(@"%@",[[UIDevice currentDevice] model]);
// "iPhone" on both devices
NSLog(@"%@",[[UIDevice currentDevice] localizedModel]);
// "iPhone" on both devices 

As always , if you have any question , feel free to contact me.
有任何問題,請聯絡我

2012年6月13日 星期三

UIDevice 文件

【環境:xCode4.3.2】

說明:其實從xcode中可以看到,但可以從這份文件當中看出,UIDevice可以替我們做什麼事情,包含
UIDeviceOrientation;//旋轉
UIDeviceBatteryState;//電池
UIUserInterfaceIdiom;//裝置(ipad ,iphone)版本判定

你可以抓出一些資訊,像是
name;              // e.g. "My iPhone"
model;             // e.g. @"iPhone", @"iPod touch"
localizedModel;    // localized version of model
systemName;        // e.g. @"iOS"
systemVersion;     // e.g. @"4.0"
orientation;       // return current device orientation.  this will return UIDeviceOrientationUnknown unless device orientation notifications are being generated.
uniqueIdentifier  __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_2_0,__IPHONE_5_0);  // a string unique to each device based on various hardware info.


<以下官方文件>
 
//
//  UIDevice.h
//  UIKit
//
//  Copyright (c) 2007-2011, Apple Inc. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKitDefines.h>

typedef enum {
    UIDeviceOrientationUnknown,
    UIDeviceOrientationPortrait,            // Device oriented vertically, home button on the bottom
    UIDeviceOrientationPortraitUpsideDown,  // Device oriented vertically, home button on the top
    UIDeviceOrientationLandscapeLeft,       // Device oriented horizontally, home button on the right
    UIDeviceOrientationLandscapeRight,      // Device oriented horizontally, home button on the left
    UIDeviceOrientationFaceUp,              // Device oriented flat, face up
    UIDeviceOrientationFaceDown             // Device oriented flat, face down
} UIDeviceOrientation;

typedef enum {
    UIDeviceBatteryStateUnknown,
    UIDeviceBatteryStateUnplugged,   // on battery, discharging
    UIDeviceBatteryStateCharging,    // plugged in, less than 100%
    UIDeviceBatteryStateFull,        // plugged in, at 100%
} UIDeviceBatteryState;              // available in iPhone 3.0

typedef enum {
#if __IPHONE_3_2 <= __IPHONE_OS_VERSION_MAX_ALLOWED
    UIUserInterfaceIdiomPhone,           // iPhone and iPod touch style UI
    UIUserInterfaceIdiomPad,             // iPad style UI
#endif
} UIUserInterfaceIdiom;

/* The UI_USER_INTERFACE_IDIOM() macro is provided for use when deploying to a version of the iOS less than 3.2. If the earliest version of iPhone/iOS that you will be deploying for is 3.2 or greater, you may use -[UIDevice userInterfaceIdiom] directly.
 */
#define UI_USER_INTERFACE_IDIOM() ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? [[UIDevice currentDevice] userInterfaceIdiom] : UIUserInterfaceIdiomPhone)

#define UIDeviceOrientationIsPortrait(orientation)  ((orientation) == UIDeviceOrientationPortrait || (orientation) == UIDeviceOrientationPortraitUpsideDown)
#define UIDeviceOrientationIsLandscape(orientation) ((orientation) == UIDeviceOrientationLandscapeLeft || (orientation) == UIDeviceOrientationLandscapeRight)

UIKIT_CLASS_AVAILABLE(2_0) @interface UIDevice : NSObject {
 @private
    NSInteger _numDeviceOrientationObservers;
    float     _batteryLevel;
    struct {
 unsigned int batteryMonitoringEnabled:1;
 unsigned int proximityMonitoringEnabled:1;
 unsigned int expectsFaceContactInLandscape:1;
        unsigned int orientation:3;
        unsigned int batteryState:2;
        unsigned int proximityState:1;
    } _deviceFlags;
}

  (UIDevice *)currentDevice;

@property(nonatomic,readonly,retain) NSString    *name;              // e.g. "My iPhone"
@property(nonatomic,readonly,retain) NSString    *model;             // e.g. @"iPhone", @"iPod touch"
@property(nonatomic,readonly,retain) NSString    *localizedModel;    // localized version of model
@property(nonatomic,readonly,retain) NSString    *systemName;        // e.g. @"iOS"
@property(nonatomic,readonly,retain) NSString    *systemVersion;     // e.g. @"4.0"
@property(nonatomic,readonly) UIDeviceOrientation orientation;       // return current device orientation.  this will return UIDeviceOrientationUnknown unless device orientation notifications are being generated.
@property(nonatomic,readonly,retain) NSString    *uniqueIdentifier  __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_2_0,__IPHONE_5_0);  // a string unique to each device based on various hardware info.

@property(nonatomic,readonly,getter=isGeneratingDeviceOrientationNotifications) BOOL generatesDeviceOrientationNotifications;
- (void)beginGeneratingDeviceOrientationNotifications;      // nestable
- (void)endGeneratingDeviceOrientationNotifications;

@property(nonatomic,getter=isBatteryMonitoringEnabled) BOOL batteryMonitoringEnabled __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);  // default is NO
@property(nonatomic,readonly) UIDeviceBatteryState          batteryState __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);  // UIDeviceBatteryStateUnknown if monitoring disabled
@property(nonatomic,readonly) float                         batteryLevel __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);  // 0 .. 1.0. -1.0 if UIDeviceBatteryStateUnknown

@property(nonatomic,getter=isProximityMonitoringEnabled) BOOL proximityMonitoringEnabled __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0); // default is NO
@property(nonatomic,readonly)                            BOOL proximityState __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);  // always returns NO if no proximity detector

@property(nonatomic,readonly,getter=isMultitaskingSupported) BOOL multitaskingSupported __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_0);

@property(nonatomic,readonly) UIUserInterfaceIdiom userInterfaceIdiom __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_2);

- (void)playInputClick __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_2);  // Plays a click only if an enabling input view is on-screen and user has enabled input clicks.

@end

@protocol UIInputViewAudioFeedback <NSObject>
@optional

@property (nonatomic, readonly) BOOL enableInputClicksWhenVisible; // If YES, an input view will enable playInputClick.

@end

UIKIT_EXTERN NSString *const UIDeviceOrientationDidChangeNotification;
UIKIT_EXTERN NSString *const UIDeviceBatteryStateDidChangeNotification   __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);
UIKIT_EXTERN NSString *const UIDeviceBatteryLevelDidChangeNotification   __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);
UIKIT_EXTERN NSString *const UIDeviceProximityStateDidChangeNotification __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0); 

As always , if you have any question , feel free to contact me.
有任何問題,請聯絡我

判定ios版本的方式

【環境:xCode4.2 , ios5.1 , USE ARC】

說明:因ios版本開發種類持續更新,若有特殊需求,要向下相容,可使用此方法

<以下範例>
 
#import "sys/utsname.h"//記得加入此行

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0) {
// iOS 5 code
//代碼範例使用的是navigation中更改背景圖的方法,ios4以前使用的方法很多種,但蘋果希望目前使用這種方法,故以前的某些方法會被禁用
[self.navigationController.navigationBar setBackgroundImage:[UIImageimageNamed:@"top_bk.png"] forBarMetrics:UIBarMetricsDefault];
}
else {
// iOS 4.x code
}

As always , if you have any question , feel free to contact me.
有任何問題,請聯絡我

ios,判斷目前使用的device為ipad or iphone

【環境:xCode4.3.2 , ios5.0 , USE ARC】

以下是library中所註明的資訊,可在xcode中對使用的關鍵字userInterfaceIdiom按下command+滑鼠左鍵去檢視
typedef enum {
#if __IPHONE_3_2 <= __IPHONE_OS_VERSION_MAX_ALLOWED
    UIUserInterfaceIdiomPhone,           // iPhone and iPod touch style UI
    UIUserInterfaceIdiomPad,             // iPad style UI
#endif
} UIUserInterfaceIdiom;

/* The UI_USER_INTERFACE_IDIOM() macro is provided for use when deploying to a version of the iOS less than 3.2. If the earliest version of iPhone/iOS that you will be deploying for is 3.2 or greater, you may use -[UIDevice userInterfaceIdiom] directly.
 */
#define UI_USER_INTERFACE_IDIOM() ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? [[UIDevice currentDevice] userInterfaceIdiom] : UIUserInterfaceIdiomPhone)


<以下使用範例>

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
if ([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone) {
UIViewController*  IPhoneViewController1=[[UIViewController  alloc]init];
self.window.rootViewController=  IPhoneViewController1;
}
else if ([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPad) 
{
UIViewController*  IPadViewController1=[[UIViewController  alloc]init];
self.window.rootViewController=  IPadViewController1;
} 

or if you have nib file, you can type
[[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil];

As always, if you have any question , feel free to contact me.
有任何問題,請聯絡我

2012年6月6日 星期三

利用delegate傳值

【環境:xCode4.2 , ios5.0】

說明:唯一要注意的應該是,在父框中初始化child後,要將child中所宣告的delegate參數,指向父框(child.delegate_name = self),如程式碼中的第86行。

Download Code
 
#import <UIKit/UIKit.h>

@protocol passValueDelegate

-(void)passString:(NSString *)value;

@end

view1
view2
view1

2012年6月5日 星期二

UIView

【環境:xCode4.2 , ios5.0】

基本UIView,這次主要在於view的移動,還有初階的使用,利用按鈕移動uiview和切換uiview
應用了兩種不同的方法
下一篇會完整介紹UIView的完整功能
比較值得探討的就是
UIViewImage *a1;
a1.frame.size.width & a1.frame.origin.x
一個是自己本身的寬度,另一個是自己本身在父框的初始位置

程式碼下載

截圖:




2012年6月4日 星期一

狀態列statusBar

【環境:xCode4.2 , ios5.1】

說明:在xCode中,對setStatusBarStyle這個標籤,按下ctrl+滑鼠左鍵,可察看相關可設定的資訊,關於在xCode中,利用plist更改預設的方式,就不多說

<以下範例>
 
//設定類型
[[UIApplication shareApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:NO];

//特定透明
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:YES];

//隱藏狀態列
[[UIApplication shareApplication] setStatusBarHidden:YES];

frame & bounds

此圖為網路截取

view的觀念

座標系中比較常用的幾個概念是
Frame:Frame指定了View相對於其父View座標系的位置和大小
Bounds:Bounds則是view相對於自身坐標系的位置和大小,bounds的起點通常都是(0,0),但是有些時候也可以透過這個屬性來對view的顯示範圍進行更靈活的控制。
Center:顧名思義就是view的Frame的中心。

frame的CGPoint是指父類view的原點坐標位置
而bounds則是只左上角自身坐標系的位置

bounds & frame的程式範例,可看到....frame & bounds之間的關係....
 
 UIView *v1 = [[UIView alloc] initWithFrame:CGRectMake(101.0f, 100.0f, 51.0f, 50.0f)];
 v1.backgroundColor = [UIColor yellowColor];
    
 NSLog(@"frame_x : %f, frame_y : %f",v1.frame.origin.x,v1.frame.origin.y);
 NSLog(@"frane_w : %f, frame_h : %f",v1.frame.size.width,v1.frame.size.height);
    
 NSLog(@"bounds_x : %f,bounds_y : %f",v1.bounds.origin.x,v1.bounds.origin.y);
 NSLog(@"bounds_w : %f,bounds_h : %f",v1.bounds.size.width,v1.bounds.size.height);
    
 [self.view addSubview:v1]; 

顯示出來的結果為
2012-06-11 10:09:33.064 TAAZA[489:f803] frame_x : 101.000000, frame_y : 100.000000
2012-06-11 10:09:33.065 TAAZA[489:f803] frane_w : 51.000000, frame_h : 50.000000
2012-06-11 10:09:33.065 TAAZA[489:f803] bounds_x : 0.000000,bounds_y : 0.000000
2012-06-11 10:09:33.066 TAAZA[489:f803] bounds_w : 51.000000,bounds_h : 50.000000

最後你可以試試在一個view上面addSubView疊加一個view後,用super.view.frame.origin.x等等之類的,看可否得知第一個view的frame的x位置 同理可證使用其他的位置去抓出父view的位置或者size

AVFoundation應用、Google_TTS

【環境:xCode4.3.2 , ios5.1】

說明:
以uitabBarController為基礎框架,自定義tabBar,我的tabBarItem用的是30x30的大小,且背景須為透明,顏色為淺色系。
使用uitextview、AVFoundation應用、Google_TTS。
其中tts的部份加入,中英文判斷。
應用到了一點QuartzCore去處理uitextview的外框。

值得注意的還有tts若想用其他語言發音
http://translate.google.com/translate_tts?tl=en&q=text
則更改紅字的部份,此部份為countryCode

故此範例須引用
#import <AVFoundation/AVFoundation.h> 
#import <QuartzCore/QuartzCore.h>
引用的protocol有以下兩個
<UITabBarDelegate,UITabBarControllerDelegate>
<UITextViewDelegate>

※若你的音效程式碼運行正確,但實機測試卻撥不出來,可以檢查<你iphone的震動的按鈕是否打開>。

※若simulation也無聲音,大概就必須檢查你的程式碼stop & pause部分代碼,是否和play搞混。


範例下載  若只需單純的tts 參考,此部份提供當初我網路上參考tts的程式






<以下部分程式碼範例-主要為textview應用和google tts的應用>
 
//
//  view2.m
//  sound & tts
//
//  Created by jhaoheng on 2012/6/1.
//  Copyright (c) 2012年 __n11_studio__. All rights reserved.
//

#import "view2.h"

//由於本範例有使用到 Layer 類別的方法,所以必須先匯入其對應的標頭檔和 Framework。
#import <QuartzCore/QuartzCore.h>

@implementation view2

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //self.title = @"three";
        UIImage *img_speak = [UIImage imageNamed:@"google.png"];
        UITabBarItem *item3 = [[UITabBarItem alloc]initWithTitle:@"G_TTS" image:img_speak tag:1]; 
        self.tabBarItem = item3;
        
        /*
        The item’s image. If nil, an image is not displayed.
        
        The images displayed on the tab bar are derived from this image. If this image is too large to fit on the tab bar, it is scaled to fit. The size of an tab bar image is typically 30 x 30 points. The alpha values in the source image are used to create the unselected and selected images—opaque values are ignored.
        */
        /*
         if you want to create icons for iPhone UITabBar ,you can read this website
         http://steveweller.com/articles/toolbar-icons/
        */
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    input_text = [[UITextView alloc]initWithFrame:CGRectMake(10, 10, 300, 150)];
    input_text.font = [UIFont fontWithName:@"Arial" size:20];
    input_text.textColor = [UIColor whiteColor];
    input_text.delegate = self;
    input_text.backgroundColor = [UIColor whiteColor];
    input_text.text = @"you can type something in this frame and click the speaker button to pronounce";
    input_text.returnKeyType = UIReturnKeyDefault;
    input_text.keyboardType = UIKeyboardTypeDefault;
    /*
     autocapitalizationType — 首字大寫
     autocorrectionType — 自動更正錯字
     enablesReturnKeyAutomatically — 確認使用者有輸入文字後才啟用return鍵
     keyboardAppearance — 鍵盤外型
     keyboardType — 鍵盤種類
     returnKeyType — return鍵的類型
     secureTextEntry — 隱藏輸入的文字
    */
    //設定是否可捲動
    input_text.scrollEnabled = YES;
    //自適應高度
    //text.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    
    //設定橘色背景與棕色邊框
    [input_text setBackgroundColor:[UIColor orangeColor]];
    [[input_text layer] setBorderColor:[[UIColor brownColor] CGColor]];
    //邊框粗細
    [[input_text layer] setBorderWidth:1.5];
    //設定圓角程度
    [[input_text layer] setCornerRadius:20];
    /*指定內文字體大小並置中
    [text setFont:[UIFont boldSystemFontOfSize:50.0]];
    [text setTextAlignment:UITextAlignmentCenter];
    */
    //設定無法再被編輯
    [input_text setEditable:YES];
     
    //使內文保持在UITextView邊框之內
    [input_text setClipsToBounds: YES];
    [self.view addSubview:input_text];
    
    UIButton *speaker = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [speaker setTitle:@"speaker" forState:UIControlStateNormal];
    [speaker setTitle:@"connect" forState:UIControlStateHighlighted];
    speaker.frame = CGRectMake(20, 295, 280, 40);
    [speaker addTarget:self action:@selector(machine_speak) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:speaker];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -uibutton
-(void)machine_speak
{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"file.mp3"];
    NSString *urlString;
    if ([input_text.text canBeConvertedToEncoding: NSASCIIStringEncoding]) {//如果是英語
        urlString = [NSString stringWithFormat:@"http://www.translate.google.com/translate_tts?tl=en&q=%@",input_text.text];
    }  
    else { //如果是非英語 
        urlString = [NSString stringWithFormat:@"http://www.translate.google.com/translate_tts?tl=zh-TW&q=%@",input_text.text];
    } 
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:2.0.1) Gecko/20100101 Firefox/4.0.1" forHTTPHeaderField:@"User-Agent"];
    NSURLResponse* response = nil;
    NSError* error = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];
    [data writeToFile:path atomically:YES];
    
    NSError *err;
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) 
    {    
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&err];
        player.volume = 0.8f;
        [player prepareToPlay];
        [player setNumberOfLoops:0];
        [player play];    
    }
     
}

#pragma mark - UITextView Delegate Methods     

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)closetext
{    
    if ([closetext isEqualToString:@"\n"]) {    
        
        [input_text resignFirstResponder];    
        
        return NO;    
        
    }
    return YES;    
}

@end