Elton's Blog

Tag: iPhone

使用Google Analytics跟踪你的手机应用

by on 一.09, 2010, under iPhone

大家都知道Google Analytics可以跟踪网站的浏览情况。 其实Google Analytics提供了一个iPhone的本地类库,也可以帮助你跟踪你的手机应用,帮助你分析你的手机应用的用户使用习惯。

加入Google Analytics的方法很简单:

  1. 这里下载类库。(在页面下面Supported Development Environments部分有下载链接)
  2. 加入libGoogleAnalytics.a静态类库和GANTracker.h头文件到你的项目中。
  3. 加入Google Analytics需要的其他类库(CFNetwork framework和libsqlite3.0.dylib。
  4. 在你的项目中加入几行初始化代码,然后添加跟踪页面或者事件的代码。见下面的示例程序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#import "BasicExampleAppDelegate.h"
 
#import "GANTracker.h"
 
// Dispatch period in seconds
 static const NSInteger kGANDispatchPeriodSec = 10;
 
 @implementation BasicExampleAppDelegate
 
 @synthesize window = window_;
 
 - (void)applicationDidFinishLaunching:(UIApplication *)application {
   // **************************************************************************
   // PLEASE REPLACE WITH YOUR ACCOUNT DETAILS.
   // **************************************************************************
    [[GANTracker sharedTracker] startTrackerWithAccountID:@"UA-0000000-1"
                                          dispatchPeriod:kGANDispatchPeriodSec
                                                delegate:nil];
   NSError *error;
   if (![[GANTracker sharedTracker] trackEvent:@"my_category"
                                        action:@"my_action"
                                         label:@"my_label"
                                         value:-1
                                     withError:&error]) {
     // Handle error here
   }
 
   if (![[GANTracker sharedTracker] trackPageview:@"/app_entry_point"
                                        withError:&error]) {
     // Handle error here
   }
 
   [window_ makeKeyAndVisible];
 }
 
 - (void)dealloc {
   [[GANTracker sharedTracker] stopTracker];
   [window_ release];
   [super dealloc];
 }
 
 @end

Google Analytics的统计也支持Andorid平台,详情请参考这里

当然因为这个类库目前只是0.7版本,可能还不够稳定。 类似的类库还有Pinch Media, Medialets, Mobclix,你可以进行参考。

1 Comment :, , , , , , more...

使用AVAudioPlayer播放音乐文件

by on 十二.07, 2009, under iPhone

AVAudioPlayer 提供了大量的特性,包括暂停播放,调整音量,监控音频的峰值和均值等等。 我们看下面的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
AVAudioPlayer  *player;
NSString       *path;
 
// 设置音乐文件路径
path = [[NSBundle mainBundle] pathForResource:@"sound-file" ofType:@"mp3"];
 
// 判断是否可以访问这个文件
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) 
{    
  // 设置 player
  player = [[AVAudioPlayer alloc] initWithContentsOfURL:
     [NSURL fileURLWithPath:path] error:&error];
 
  // 调节音量 (范围从0到1)
  player.volume = 0.4f;
 
  // 准备buffer,减少播放延时的时间      
  [player prepareToPlay];
 
  // 设置播放次数,0为播放一次,负数为循环播放
  [player setNumberOfLoops:0];
 
  [player play];    
 
}    
 
...
 
// 清理工作
if (player != nil)
{
  if (player.isPlaying == YES)
    [player stop];
  [player release];
}
25 Comments :, more...

iPhone应用程序名称本地化

by on 十一.26, 2009, under iPhone

iPhone的应用程序名称也可以本地化,可以按照以下步骤来实施:

1. 修改项目目录下的’ -info.plist’文件名

将’ -info.plist’ 修改为 Info.plist

2. 将Info.plist本地化

在Info.plist上右键点选Get Info,在General标签下,点击Make File Localizable按钮。
里面会有一个默认的英文版本,点击Add Localization… 按钮,添加你需要的本地化语言。 如简体中文”zh-hans”,然后点击添加
注意这里用了“zh-hans”表示简体中文,你也可以用”zh-CN”来表示,不过有些情况下这个可能不起作用。 对应的”zh-hant”表示繁体中文。

3. 创建InfoPlist.strings文件,并本地化它

在项目目录下新建一个InfoPlist.strings文件,重复上面的步骤,将其本地化。

4. 编辑InfoPlist.strings中的内容。

现在你就可以编辑InfoPlist.strings中的内容,实现应用程序名称的本地化了。
在其中添加
CFBundleDisplayName = “xxxxx”;
就可以了。

5 Comments :, , more...

将图片保存在iPhone的相册中

by on 十一.16, 2009, under iPhone

有时候你的应用需要将应用中的图片保存到用户iPhone或者iTouch的相册中。 可以使用UIKit的这个类方法来完成。

1
2
3
4
5
6
void UIImageWriteToSavedPhotosAlbum (
   UIImage  *image,
   id       completionTarget,
   SEL      completionSelector,
   void     *contextInfo
);

image
要保存到用户设备中的图片

completionTarget
当保存完成后,回调方法所在的对象

completionSelector
当保存完成后,所调用的回调方法。 形式如下:

1
2
3
- (void) image: (UIImage *) image
    didFinishSavingWithError: (NSError *) error
    contextInfo: (void *) contextInfo;

contextInfo
可选的参数,保存了一个指向context数据的指针,它将传递给回调方法。

比如你可以这样来写一个存贮照片的方法:

1
2
3
4
5
// 要保存的图片
  UIImage *img = [UIImage imageNamed:@"ImageName.png"];  
 
  // 保存图片到相册中
  UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);

回调方法看起来可能是这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error 
             contextInfo:(void *)contextInfo
  {
    // Was there an error?
    if (error != NULL)
    {
      // Show error message...
 
    }
    else  // No errors
    {
      // Show message image successfully saved
    }
  }
2 Comments :, , , more...

判断你的设备是iPhone还是iPod

by on 十一.16, 2009, under iPhone

有时候你的程序需要知道用户使用的设备是iPhone还是iPod。因为有些特性iPod是没有的,比如电话功能。方法很简单:

1
NSString *deviceType = [UIDevice currentDevice].model;

如果你想得到一个本地化的字符串,可以使用以下命令:

1
2
NSString *deviceType = [UIDevice currentDevice].modellocalizedModel;
NSLog(@"type: %@", deviceType);
Leave a Comment :, , , more...

iPhone开发中使用的特殊URL

by on 十.24, 2009, under iPhone

在iPhone中,可以直接用UIApp打开URL地址。如下所示:

1
[ UIApp openURL: [ NSURL URLWithString:@"http://www.apple.com" ] ];

或者:

1
[ UIApp openURL: [ NSURL URLWithString:@"mailto:apple@mac.com?Subject=hello" ] ];

与此同时,iPhone还包含一些其他除了http://或者mailto:之外的URL:
sms:// 可以调用短信程序
tel:// 可以拨打电话
itms:// 可以打开MobileStore.app
audio-player-event:// 可以打开iPod
audio-player-event://?uicmd=show-purchased-playlist 可以打开iPod播放列表
video-player-event:// 可以打开iPod中的视频

Leave a Comment :, more...

给TableView添加背景

by on 十.16, 2009, under iPhone

iPhone SDK提供了默认的几个TableView样式,但是如果想提供更个性化的样式就需要自己定义。 比如添加背景

如上图的样子。 其实自定义table view的样子很简单,无非就是把table view和table view cell的背景变成透明的,然后在指定视图和cell的背景图片(当然,也可以指定table view的背景图片)

1
2
3
4
@interface MainViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
  UITableView *theTableView;
}

先建立Controller,注意是继承自UIViewController而不是UITableViewController

实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
- (id)init
{
  if (self = [super init]) 
  {
    self.view = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
 
    // Setup the background
    UIImageView *background = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]];
    [self.view addSubview:background];
    [background release];
 
    // Create table view
    theTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 11, 320, 460) style: UITableViewStylePlain];
    [theTableView setDelegate:self];
    [theTableView setDataSource:self];
 
    // This should be set to work with the image height
    [theTableView setRowHeight:68];
 
    // Transparent, so we can see the background
    [theTableView setBackgroundColor:[UIColor clearColor]];
    [theTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [theTableView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
 
    [self.view addSubview:theTableView];
 
  }
  return self;
}

代码中的注释已经很清楚了。 先设置视图的背景,再设定table view的背景

再看另外一断代码,设置了cell的背景,注意,这里面使用了自定义的cell类CustomCell

1
2
3
4
5
6
7
8
9
10
11
12
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
	CustomCell *cell= [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
 
	// Default to no selected style and not selected
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
 
	// Set the image for the cell
	[cell setTheImage:[UIImage imageNamed:[NSString stringWithFormat:@"Arrows%d.png", indexPath.row + 1]]];
 
	return cell;
}

我们再看看如何定义自定义的cell

1
2
3
4
5
6
7
8
9
10
#import <UIKit/UIKit.h>
 
@interface CustomCell : UITableViewCell 
{
  UIImageView *image; 
}
 
- (void) setTheImage:(UIImage *)icon;
 
@end

再看实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#import "CustomCell.h"
 
@implementation CustomCell
 
/*---------------------------------------------------------------------------
* 
*--------------------------------------------------------------------------*/
-(id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
	if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) 
  {
    // Cells are transparent
    [self.contentView setBackgroundColor:[UIColor clearColor]];
	}
 
	return self;
}
 
/*---------------------------------------------------------------------------
* 
*--------------------------------------------------------------------------*/
- (void) setTheImage:(UIImage *) icon
{  
  // Alloc and set the frame
  image = [[UIImageView alloc] initWithImage:icon];
  image.frame = CGRectMake(0, 0, 286, 68);
 
  // Add subview
  [self.contentView addSubview:image];    
}
 
/*---------------------------------------------------------------------------
*
*--------------------------------------------------------------------------*/
- (void)setSelected:(BOOL)selected animated:(BOOL)animated 
{
  [super setSelected:selected animated:animated];   
  if (selected == YES)
    image.alpha = .5;
  else
    image.alpha = 1;
}
 
/*---------------------------------------------------------------------------
* 
*--------------------------------------------------------------------------*/
- (void)dealloc 
{
  [image release];
  [super dealloc];
}
 
@end

还是很简单的吧。

1 Comment :, , more...

如何在iPhone编程中使用UITextField

by on 十.06, 2009, under iPhone

下面的例子将展示如何通过UITextField的内容来改变UILabel中的内容

实现UITextField Delegate协议

首先我们需要在viewController的接口中声明实现UITextFieldDelegate代理协议

1
2
3
4
@interface TextField : UIViewController<UITextFieldDelegate> {
 
}
@end

添加UILabel 和 UITextField对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#import "TextField.h"
 
@implementation TextField
UILabel *label;
UITextField *textField;
 
- (void)viewDidLoad {
    [super viewDidLoad];
 
	//Create label
	label = [[UILabel alloc] init];
	label.frame = CGRectMake(10, 10, 300, 40);
	label.textAlignment = UITextAlignmentCenter;
	label.text = @"";
	[self.view addSubview:label]; 
 
	// Initialization code
	textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 200, 300, 50)];
	textField.delegate = self;
	textField.placeholder = @"<Enter Text>";
	textField.textAlignment = UITextAlignmentCenter;
	[self.view addSubview: textField];
}
 
- (void)dealloc {
	[textField release];
	[label release];
    [super dealloc];
}
 
@end

这段程序没有什么好说的,就是建立并初始化一个UILabel和UITextField对象

实现代理方法

1
2
3
4
5
6
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
	label.text = textField.text;
	[textField resignFirstResponder];
 
    return YES;
}

当用户按了键盘上的Return键后,此方法被调用。 它做了两件事,一件是把UILabel中的值设置成UITextField中的值,另外一个是关闭虚拟键盘。

iPhone编程中大量使用了代理和回调方法,是一种基本的设计模式,所以大家要熟悉这种编程模式。

3 Comments :, , more...

清除iPhone模拟器中的程序

by on 九.25, 2009, under iPhone

当你使用iPhone模拟器测试过很多程序以后,模拟器中放置了大量无用的程序。 一直在找如何清除这些程序,其实后来发现很简单。 模拟器本身就带将这些程序清除到垃圾箱的功能。
清除模拟器中的程序

2 Comments : more...

如何在iPhone的应用中使用Google Map

by on 九.16, 2009, under iPhone

在iPhone中应用Google地图其实很简单, 下面的例子将告诉你如何通过经纬度或者一个地址在iPhone中打开一个Google地图。

下面这个例子展示如何用经纬度来打开Google地图:

1
2
3
4
5
6
7
8
9
//Using longitude and latitude to drop a pin on Google maps
	float longitude = 38.892219;
	float latitude = -77.034674;
 
	NSString *url = [NSString stringWithFormat: @"http://maps.google.com/?q=%f,%f",
	                     longitude,
	                     latitude];
 
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];

注意这个例子中的openURL:方法。 iPhone中的程序经常使用这个方法来共享他们的功能。 任何一个iPhone程序都可以注册一个URL用来让其他应用程序通过这个URL打开此应用。 Google地图程序就注册了一个这样的“http://maps.google.com/?q”URL。 上面的例子执行后,就会关掉当前的应用程序,而打开Google地图。

下面这个例子展示如何用地址打开一个Google地图:

1
2
3
4
//URL to map address
NSString *url = @"http://maps.google.com/?q=Constitution+Avenue+Northwest+Washington+DC";
 
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
Leave a Comment :, , more...



Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit my friends!

A few highly recommended friends...