아이폰어플개발정보2010. 10. 13. 14:18
[아이폰 앱 개발] webView를 이용해서 간단한 웹브라우져 만드는 방법

iPhone Coding – Learning About UIWebViews by Creating a Web Browser

Wow! It has been a long time since my last tutorial… As I wrote in my last post, I had to take a break due to my wife having our baby.  But, now I’m back and have a great tutorial for you guys.  

Today I will be showing you how to work with a  UIWebview to create a basic web browser.  Here is a screenshot of the app we are going to create.

Create a View-Based Application

Ok, so let’s get started.  Start by opening up Xcode and click File -> New Project.  Next select View-Based Application and click Choose… Name this project something like iCodeBrowser and click Save.  

Now we are ready to begin coding…

Create IBOutlets and IBActions

Before we create the interface for our web browser, we need to establish the IBOutles and Actions to interface with the UI elements in code.  Start by opening up iCodeBrowserViewController.h and add the following code:

Let’s take a look at this code line by line.  The first thing we added was the  to the end of our interface declaration.  This is telling the app that this class will be the delegate for our UIWebview.  

What does it mean to be the delegate you ask? Great question… A delegate is like a handler.  It is responsible for implementing certain methods in order to handle events sent by the object they are the delegate for.  So in our example, we are simply saying that we will implement some of the functionality of the UIWebView.  This is needed so we can capture certain actions of the UIWebView such as a click on a link or so we can tell when a page has started/finished loading.  If it’s still unclear, ask me clarifying questions in the comments section.

Next, we see our 3 lines of declaring IBOutlets.  These are the UI elements that we will be interacting with.  In case you didn’t know, the UIActivityIndicator is the little spinner/loading animation that you see on various apps when content is loading.  We will be using this to show that a page is currently loading.

Following this code, there are 3 IBActions.  IBActions are functions that get called in response to a user interaction with the application (such as tapping a button).  For our basic browser, we are only offering 3 types of functionality.  gotoAddress which will take a user to the address they type in the address bar and goBack/Forward should be pretty self explanatory.  

Creating the User Interface 

Now, let’s create the interface using Interface Builder.  I am going to be showing you how to do this in the video below.

 

Implementing the IBActions

Now that we have our interface, let’s make the app function.  We need to implement our methods.  Open up iCodeBrowserViewController.m and add the following code.

We need to synthesize our properties to allow us to interact with them.  Synthesizing automatically creates “getter” and “setter” methods for our properties.  Next, let’s implement the viewDidLoad method.  This is where we will be loading our “homepage”.  Add the following code to the viewDidLoad method.

The viewDidLoad method gets called automatically by our application whenever this view first loads.  We can know for sure that it will get called, so we can put our initialization code here.

ADVERTISEMENT

 

The first thing we see is the urlAddress string.  This will be our “homepage”.   You can change this to any address you wish to start with.  Next, we build a URL object with our string.  We need to do this so we can make a web request.  Following this, we build our web request and load it into the webView.  This will display the homepage inside of our webview.  Finally, we set the text of the address bar to the homepage address.  This part is more for aesthetics to let the user know what page they are on.

Next, we implement the method that we connected to the UITextField’s DidEndOnExit method gotoAddress.  Add the following code:

This is similar to the code we wrote in the viewDidLoad method, except for the fact that we are getting our URL string from the address bar.  This method gets called when the user presses the “Go” button on the keyboard.  The last thing to note here is we call the [addressBar resignFirstResponder] method.  This simply tells the app to hide the keyboard when this method gets called.

The implementation of our Back and Forward methods are pretty easy.  Go ahead and add the following code.

UIWebViews are pretty cool because of the functionality they offer us built right in to them.  We simply call[webView goBAck] to go back and [webView goForward] to go forward.  This greatly simplifies the interactions with the webview.  If we were to code that functionality from scratch, we would have to create a stack of URLs and continually push and pop them off the stack to keep track of where we need to go.  Thanks Apple for not making us implement this.

Finally, we need to implement the delegate methods for UIWebview.  These methods allow us to write our own code to respond to actions by the UIWebview.  The first methods we will implement are the webViewDidStartLoad and the webViewDidFinishLoad methods.  We will use these to show and hide the activity indicator. Add the following code:

So when the request is first made for a ULR (before the page starts loading) the webViewDidStartLoad method gets called automatically.  We use this opportunity to start our activity indicator to let the user know the page is loading.  If you don’t have something like this, it simply feels like the app is frozen when in fact, it’s just loading the page.  Finally, the webViewDidFinishLoad method gets called when the page is fully loaded.  After this, we can stop the indicator (and it automatically hides itself).

The very last thing we need to do is define what happens when a user clicks on a link. Add the following method:

This method gets called automatically whenever the user clicks a link.  This method can be very useful if you want to make a native iPhone application that integrates with a web app.  You can use this method to trap the user’s clicks and have your application respond to web links that get clicked.  In our case, we need it to do 2 things.  The first is to set the text of the address bar to the URL of the link that was clicked on and to load that address into the webview.

One thing to make note of: We do a check to see if the URL scheme is “http”. This is to ensure that the user typed http before their URL.  You can add an else statement here that auto prepends the http if the user did not add it.  This would allow you to type in a url such as “icodeblog.com” rather than having to type “http://www.icodeblog.com”.  I chose to omit it for this tutorial.

Remember, all of this added functionality of a UIWebView can only be gotten if you tell your class that it implements the UIWebViewDelegate protocol as we did in our .h file.

The app should be complete! Click on Build and Go to see this baby in action.  Remember, you must put “http://” in front of your URL’s.  

I hope you have enjoyed this tutorial.  If you have any questions or comments, feel free to leave them in the comments section of this post.  You can download the source here . Happy iCoding!

 

 

This entry was posted in Interface BuilderiPhone Programming Tutorials and tagged . Bookmark the permalinkPost a comment or leave a trackback: Trackback URL.
Posted by 오늘마감

댓글을 달아 주세요

아이폰어플개발정보2010. 10. 12. 04:09
Timer를 이용해서 재귀 반복 하는 소스

- (void)makeMyProgressBarMoving {

float actual = [threadProgressViewprogress];

threadValueLabel.text = [NSString stringWithFormat:@"%.2f", actual];

if (actual < 1) {

threadProgressView.progress = actual + 0.01;

[NSTimerscheduledTimerWithTimeInterval:0.5target:self

                         selector:@selector(makeMyProgressBarMoving) userInfo:nilrepeats:NO];

}

elsethreadStartButton.hidden = NO;

}

아이폰 어플 개발할때, timer를 이용해서 재귀호출하는 방법이다.

위의 함수는 progress Bar의 막대를 채우는 것으로, 재귀호출되면서 값이 증가되도록한다.

makeMyProgressBarMoving함수가 타이머가 0.5간격으로 울릴때, 다시 자신을 호출하며

0부터 0.01이 호출될때마다 더해져서 1이 되기전까지 계속된다.

재귀호출 중단점은 progress값이>1되면 중단된다.

Posted by 오늘마감

댓글을 달아 주세요

NSMutableDictionary 클래스 이용해서 즐겨찾기 만들어보자


아래의 값으로 NSMutableDictionary를 생성한다.

Key (NSString) Value (NSURL)
Stanford University http://www.stanford.edu
Apple http://www.apple.com
CS193P http://cs193p.stanford.edu
Stanford on iTunes U http://itunes.stanford.edu
Stanford Mall http://stanfordshop.com

루프를 돌다가 Stanford로 시작하는 키를 가진 값이 있으면 아래와 같이 로그를 출력한다.


Key: 'Stanford University' URL: 'http://www.stanford.edu'


<조건 및 힌트>
+URLWithString: 을 이용하여 URL 인스턴스를 생성하라.
NSString의 prefix/suffix를 체크하는 메소드를 이용하라.
NSMutableDictionary 는 NSDictionary의 서브클래스임을 기억하라.


NSMutableDictionary를 생성하기 위해 리퍼런스를 보자.

클래스 메소드에 dictionaryWithCapacity: 밖에 없으니... 슈퍼클래스인 NSDictionary의 클래스 메소드를 살펴본다.

dictionary라는 빈 딕셔너리를 생성해주는 클래스 메소드를 찾았다.


이용해 본다.

NSMutableDictionary *myDictionary = [NSMutableDictionary dictionary];


키와 값을 추가한다.


<시도 1>

- (void)setObject:(id)anObject forKey:(id)aKey 을 이용해 본다.


[myDictionary setObject:[NSURL URLWithString:@"http://www.stanford.edu"] forKey:@"Stanford University"];
[myDictionary setObject:[NSURL URLWithString:@"
http://www.apple.com"] forKey:@"Apple"];
[myDictionary setObject:[NSURL URLWithString:@"
http://cs193p.stanford.edu"] forKey:@"CS193P"];
[myDictionary setObject:[NSURL URLWithString:@"
http://itunes.stanford.edu"] forKey:@"Stanford on iTunes U"];
[myDictionary setObject:[NSURL URLWithString:@"
http://stanfordshop.com"] forKey:@"Stanford Mall"];


<결과>
일단 컴파일 에러가 안나니까 성공.

계속해서 Stanford로 시작하는 키의 정보를 로그로 출력해 보자.

NSDictionary의 - (NSArray *)allKeys 를 이용해 본다.


for (NSString *element in [myDictionary allKeys] ) {
    NSLog(element);
}


■ 그럼 스트링이 특정 문자로 시작하는지 알아보는 메소드는?


혹시 prefixWith.. 라는 메소드가 있나 했는데 없다. 음...


NSString Class Reference의 COMPANION GUIDES에 나와있는 String Programming Guide for Cocoa을 열어 봤다.

문서내의 Searching, Comparing, and Sorting Strings를 참조.

검색 메소드중 rangeOfString:options: 이라는게 있는데 이 옵션을 살펴보니 아래와 같은 내용이 있다.

검색 옵션 효과
NSAnchoredSearch Performs searching only on characters at the beginning or end of the range. No match at the beginning or end means nothing is found, even if a matching sequence of characters occurs elsewhere in the string.


NSString의 처음이나 끝에 검색하고자 하는 스트링이 있는지 찾아본다. 중간에 있는건 무효.

<시도>    
NSRange prefixRange = [key rangeOfString:@"Stanford" options:NSAnchoredSearch)];


리턴값은 NSRange인데 rangeOfString:options: 메소드의 설명을 보면 아래와 같다.

Return Value
An NSRange structure giving the location and length in the receiver of the first occurrence of aString, modulo the options in mask. Returns {NSNotFound, 0} if aString is not found or is empty (@"").

즉, 값을 찾지 못했을경우에는 {NSNotFound, 0} 가 돌아온다고 한다.


NSRange는 아래와 같은 구조체 이니까,

typedef struct _NSRange {
   NSUInteger location;
   NSUInteger length;
} NSRange;


location이 NSNotFound인지 살펴보면 될 것 같다.

if ([element rangeOfString:@"Stanford" options:NSAnchoredSearch].location != NSNotFound) {
    로그출력...
}


<결과>
성공!!!



출처 : http://blog.naver.com/PostView.nhn?blogId=katchup00&logNo=10075724258
Posted by 오늘마감

댓글을 달아 주세요

NSProcessInfo 클래스 이용해서 프로세스 ID 찍어보자


NSProcessInfo 를 이용하여 아래와 같이 프로세스명, 프로세스ID를 출력하라

Process Name: 'WhatATool' Process ID: '4556'


클래스 리퍼런스를 참조하니 processNameprocessIdentifier라는 그럴듯한 메소드가 있다.


<시도 1>

NSProcessInfo *pInfo = [NSProcessInfo processInfo];

NSLog(@"Process Name: '%@' Process ID: '%@'", [pInfo processName], [pInfo processIdentifier]);


<결과>

실패.... 컴파일 에러는 안나지만 프로그램 시작후 이상한 메세지가 뜬 상태로 안끝난다...


<시도 2>

프린트할 ID부분의 포멧을 %@ (오브젝트) 에서 %i (정수형)으로 바꿔봤다.

NSLog(@"Process Name: '%@' Process ID: '%i'", [pInfo processName], [pInfo processIdentifier]);


<결과>

성공!!!



출처 : http://blog.naver.com/PostView.nhn?blogId=katchup00&logNo=10075722816
Posted by 오늘마감

댓글을 달아 주세요

아이폰어플개발정보2010. 6. 24. 11:39
email을 이용해서 주소록에서 정보를 가져오는 방법

by alex 10. 3월 2009 07:54


 //Also you need to include AddressBook.framework

#import

#import

#import

[contactList removeAllObjects];

 
// open the default address book.

ABAddressBookRef m_addressbook = ABAddressBookCreate();

if (!m_addressbook) {

    NSLog(@"opening address book");

}

 
// can be cast to NSArray, toll-free

CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(m_addressbook);

CFIndex nPeople = ABAddressBookGetPersonCount(m_addressbook);

 
// CFStrings can be cast to NSString!

 
for (int i=0;i < nPeople;i++) {

 MContact *contact = [[MContact alloc] init];

  
 ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);

 CFStringRef firstName, lastName;

 firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);

 lastName  = ABRecordCopyValue(ref, kABPersonLastNameProperty);

 contact.name = [NSString stringWithFormat:@"%@ %@", firstName, lastName];

 
 ABMutableMultiValueRef eMail  = ABRecordCopyValue(ref, kABPersonEmailProperty);

 if(ABMultiValueGetCount(eMail) > 0) {

  contact.email =  (NSString *)ABMultiValueCopyValueAtIndex(eMail, 0);

  [contactList addObject:contact];

 }

  
 CFRelease(ref);

 CFRelease(firstName);

 CFRelease(lastName);

  
  
}



출처 : http://blog.naver.com/PostView.nhn?blogId=amoros21&logNo=140107111333
Posted by 오늘마감

댓글을 달아 주세요