Home > iPhone Archive
iPhone Archive
iPhone RSSリーダー作成方法
- 2009-08-07 (金)
- iPhone
以下サイトの説明をかなり簡単な日本語になおしました。
サンプルコードもあります。
iPhone SDK Tutorial: Build a Simple RSS reader for the iPhone
新規プロジェクト作成からNavigation-Based Applicationを選択。
RootViewController.hを修正
@interface RootViewController : UITableViewController {
IBOutlet UITableView * newsTable;
UIActivityIndicatorView * activityIndicator;
CGSize cellSize;
NSXMLParser * rssParser;
NSMutableArray * stories; // 成形後の格納場所
NSMutableDictionary * item; // このitemをstoriesに積み重ねていく。titleやdateなどのノードがハッシュとして格納される。
NSString * currentElement; // すべてのノードを調査
NSMutableString * currentTitle, * currentDate, * currentSummary, * currentLink; // 調査対象の格納場所
}
@end
RootViewController.mのnumberOfRowsInSectionを修正
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [stories count];
}
表示するカラム数[stories count]をテーブルに教える。
同ファイル内のcellForRowAtIndexPathを次のように修正。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
// Set up the cell
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
[cell setText:[[stories objectAtIndex: storyIndex] objectForKey: @"title"]];
return cell;
}
テーブルに表示する情報を配列で持っているstoriesから、obgectForKeyでタイトルを取得して、setTextで出力処理をしている。
さらに同ファイル内のviewDidAppearを以下のように修正
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if ([stories count] == 0) {
NSString * path = @"http://feeds.feedburner.com/TheAppleBlog";
[self parseXMLFileAtURL:path];
}
cellSize = CGSizeMake([newsTable bounds].size.width, 60);
}
どのフィードを読み込むかをここで指定。
同ファイルに以下を追加。
- (void)parseXMLFileAtURL:(NSString *)URL {
stories = [[NSMutableArray alloc] init]; // 初期化
//URLをNSURLに変換
NSURL *xmlURL = [NSURL URLWithString:URL];
// 外部ファイルをダウンロード
rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
// NSXMLParserのコールバック処理を自分にセット
[rssParser setDelegate:self];
// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
}
で、同ファイルにNSXMLParserのコールバックデリゲート処理を追加
- (void)parserDidStartDocument:(NSXMLParser *)parser {
NSLog(@"found file and started parsing");
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]];
NSLog(@"error parsing XML: %@", errorString);
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
//NSLog(@"found this element: %@", elementName);
currentElement = [elementName copy];
if ([elementName isEqualToString:@"item"]) {
// clear out our story item caches...
item = [[NSMutableDictionary alloc] init];
currentTitle = [[NSMutableString alloc] init];
currentDate = [[NSMutableString alloc] init];
currentSummary = [[NSMutableString alloc] init];
currentLink = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
//NSLog(@"ended element: %@", elementName);
if ([elementName isEqualToString:@"item"]) {
// save values to an item, then store that item into the array...
[item setObject:currentTitle forKey:@"title"];
[item setObject:currentLink forKey:@"link"];
[item setObject:currentSummary forKey:@"summary"];
[item setObject:currentDate forKey:@"date"];
[stories addObject:[item copy]];
NSLog(@"adding story: %@", currentTitle);
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//NSLog(@"found characters: %@", string);
// save the characters for the current item...
if ([currentElement isEqualToString:@"title"]) {
[currentTitle appendString:string];
} else if ([currentElement isEqualToString:@"link"]) {
[currentLink appendString:string];
} else if ([currentElement isEqualToString:@"description"]) {
[currentSummary appendString:string];
} else if ([currentElement isEqualToString:@"pubDate"]) {
[currentDate appendString:string];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];
NSLog(@"all done!");
NSLog(@"stories array has %d items", [stories count]);
[newsTable reloadData];
}
最後に同ファイル内のdeallocを以下に修正
- (void)dealloc {
[currentElement release];
[rssParser release];
[stories release];
[item release];
[currentTitle release];
[currentDate release];
[currentSummary release];
[currentLink release];
[super dealloc];
}
メモリの解放

本当の最後にRootViewController.xibを開いてコントロールキーを押しながら、files Ownerをクリック。table Viewまでドラッグしてリリースする。3つアイテムが表示して、その中のnewsTableを選択。そしてセーブ。
シミュレータで動かせば以下になるはず。

各セルを押下した後、その詳細に遷移する処理を付け加えるなら以下。
RootViewController.mに追加
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
NSString * storyLink = [[stories objectAtIndex: storyIndex] objectForKey: @"link"];
// clean up the link - get rid of spaces, returns, and tabs...
storyLink = [storyLink stringByReplacingOccurrencesOfString:@" " withString:@""];
storyLink = [storyLink stringByReplacingOccurrencesOfString:@"\n" withString:@""];
storyLink = [storyLink stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"link: %@", storyLink);
// open in Safari
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];
}
ではでは
- Comments: 0
- Trackbacks: 0
iPhoneアプリ開発 位置情報取得、メール起動
- 2009-07-30 (木)
- iPhone
iPhoneアプリが創りたい
てことで創りました。
今回は、自分の居場所をメールで相手に教えるアプリ、TellUWhere。
待ち合わせなんかで、なかなか居場所がつかめないときに、
自分の居場所をメールで教えるなんて使い方ができます。
(でも、GPSの精度がずれることもあるのでご注意を。)
ソースはかなり簡単です。
まず、GPSで位置情報を取得する処理をします。
そのために、フレームワークにCoreLocation.frameworkを追加します。
最初、私の環境では上記フレームワークが[追加]→[既存のフレームワーク]からやっても見当たらず、
UIKit.frameworkから右クリックの[finderで開く]からコピーで持ってきましたが、コンパイルするときにエラーになってしまいました。こんなエラーです。
“_kCLLocationAccuracyKilometer”, referenced from:
ひょんな拍子にもう一回[追加]→[既存のフレームワーク]から探すと、あれ?ありました。見落としてないはずだけどな。
[新規プロジェクト]、view based appからプロジェクト名TellUWhereで作成した場合です。
TellUWhereViewController.hに以下の処理を
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface TellUWhereViewController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
// GPSで計測された緯度/経度
double latitude, longitude;
}
@end
追加した情報はCoreLocationフレームワークの情報をインポート、CLLocationMa…デリゲートをサブクラスに追加。その他インスタンス変数追加。
では次に、TellUWhereViewController.m
//
- (void)viewDidLoad
{
[super viewDidLoad];
// ロケーションマネージャ作成
locationManager = [[CLLocationManager alloc] init];
// デリゲート設定
locationManager.delegate = self;
// 位置測定の望みの精度を設定
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// 位置情報更新の目安距離
locationManager.distanceFilter = kCLDistanceFilterNone;
// GPS受信スタート → デリゲートでdidUpdateToLocationにいく
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
// 位置情報を取り出す newLocationにある
longitude = newLocation.coordinate.longitude;
latitude = newLocation.coordinate.latitude;
// Google MapsのURLを作る
NSString *urlStr = [NSString stringWithFormat: @"http://maps.google.com/maps?q=%f,%f", latitude, longitude];
NSString *content = [NSString stringWithFormat: @"subject=Tell U Where I am&amp;amp;amp;body=%@:", urlStr];
NSString *mailto = [NSString stringWithFormat:@"mailto:?%@", [content stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:mailto];
[[UIApplication sharedApplication] openURL:url];
}
// Locationのデータの取得に失敗した際に呼ばれる
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"GPS Error" message:@"Error" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
//その他デフォルトである処理
流れは、viewDidLoad(GPS取得) →成功時:didUpdateToLocation、失敗時:didFailWithError
以下の処理でメールを起動しています。
NSString *mailto = [NSString stringWithFormat:@"mailto:?%@", [content stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:mailto];
[[UIApplication sharedApplication] openURL:url];
あと、locationManager.distanceFilterとlocationManager.desiredAccuracyのドキュメント。
CLLocationManager/distanceFilter
CLLocationAccuracy
CLLocationAccuracyのとり得る値
extern const CLLocationAccuracy kCLLocationAccuracyBest;
extern const CLLocationAccuracy kCLLocationAccuracyNearestTenMeters;
extern const CLLocationAccuracy kCLLocationAccuracyHundredMeters;
extern const CLLocationAccuracy kCLLocationAccuracyKilometer;
extern const CLLocationAccuracy kCLLocationAccuracyThreeKilometers;
このアプリを創りたいと思って、コーディングに入ってから完了までかなり早かったのでうれしかったです。
ではでは
- Comments: 0
- Trackbacks: 0
iPhoneアプリ開発 バリアフリーレストラン検索
- 2009-07-28 (火)
- iPhone
iPhoneアプリが創りたい。
てことで創りました。
今回はバリアフリーに対応しているレストランの検索アプリ。
まだまだ追加したい機能あるので現状のVersionは0.1としておきます。
こんな感じです。


ソースはこちらに置いておきます。
ではでは。
- Comments: 0
- Trackbacks: 0
iPhoneアプリ開発 複利計算アプリ 複利カルク
iPhoneアプリが創りたい。
てことで創りました。
このサイトにインスパイアされて作成しました。
(けっしてパクったわけではありません、インスパイアです)
http://homepage2.nifty.com/urajijou/chokin/iroirohukuri2.html
というのも手前のiPhoneとobjective-cの知識が乏しくて、少ない知識の持ちネタでしかまだ開発ができない現状があります。
その点、計算であれば、処理は四則演算その他もろもろで済みます。
今回はこんな感じにリスト表示されてて、各項目から各画面に遷移することがしたかったので、その技術が身につけられてよかったです。

下記サイトを参考にさせて頂きました。
http://d.hatena.ne.jp/moto_maka/20081118/1226953067#05(Navigation-Basedアプリの部分です)
とにかくこんなに量多く体系的に説明をしてくれるなんて本当にありがたいです。

興味のある方はソースコードをこちらに置いときますので見て下さい。
ではでは。
- Comments: 0
- Trackbacks: 0
iPhone Activationつまづき けど もちなおし
- 2009-06-30 (火)
- iPhone
iPhone Developer Programを購入するとアクティベーションコードが送られてきます。
リンクを押下して登録を完了して下さい、みたいな旨があり、リンクを押下すると次のエラーが出てしまった。
We are unable to activate your iPhone Developer Program membership because we are unable to successfully verify your identity. Please contact us and reference Enrollment ID#XXXXXXXXXX for further assistance.
購入する際、住所に日本語を入力したのがよくなったのでしょうか。
iPhone dev centerの自分のアカウントを見ると文字化けしている・・・。えー、なんで購入時の住所とアカウントが連動しているのさ。
とにかく、自分の身元が分かるもの(パスポート、免許書など)と必要事項を記入の上これこれのフォームにどこどこのFAXに送ってくれという記述がありました。いうとおりにしようとして、自分はFAXを持ってなく、コンビニのFAXサービスを利用しようとしました。けど、セブンではサービスがなく、ファミリマートとローソンがやってる模様。コンビニ探していざ送信。はい、エラーで送れない。意味わかりません。ネットで調べると、FAXの規格で送信できないことが、ままあると。4時間くらいが無駄になるはめに。
えー、じゃぁどうしよう。カスタマーサービスがあったので電話できくことにしました。営業時間が17時までだったので次の日に持ち越し。ふぅ。
はい、次の日になりました。10時に電話しようと思ってましたので、パソコン立ち上げて番号調べてと、、ちょっとその前にメールでも調べとくかな。あれ、何かメールがきてる。
We are following up with you regarding your recent iPhone Developer Program purchase.
Your order information did not sufficiently match your enrollment information and as a result the ability to activate your Program was placed on a temporary hold. We have reviewed the issue and have removed the hold on your Program activation. At this time, we ask that you please refer to the original activation code email that you received and click through the link once again.
意訳は、(あなたも身元の)情報がマッチしてなかったので、ホールドにしてました。が、調査した結果OKだったのでホールド解除。前に送ったメールからリンクを押下して登録完了してください、と。
ふー、えがった。えがった。
リンクを押下して無事登録完了。
おそらく日常茶飯事だったので、こういった対応もしてくれるようになったんですね。
Macの会社の人たちありがとうございました。
- Comments: 0
- Trackbacks: 0
iPhoneアプリ開発 割り勘アプリ 割勘ex
iPhoneでアプリが創りたい。
てことで創りました。
にしても、とても丁寧に解説してくれているサイトが、ままございます。
今回お目にかかれたサイトはその中でも秀逸です。
それは下記サイトです。
http://gihyo.jp/dev/serial/01/iphone
本当に勉強になりました。皮さんという方には感謝でございます。
では今回私もこのチュートリアルを参考にして皮さんのアプリを改変するところから始めます。
割り勘アプリ(Mixiで紹介・公開されています)、これに機能を付け加えて自分色に染めたいと思います。(ライセンスもゆるいやつなので。MIT License)
すでにある機能に、男女どちらかに固定金額を設定できる機能を付け加えました。


実装内容はチュートリアルにのっていることで事足ります。
ソースはこちらからダウンロードできます。
ではでは。
- Comments: 0
- Trackbacks: 0
Home > iPhone Archive
- Search
- Feeds
- Meta