웹페이지를 보여줄때,
그냥 UIWebView 에 바로 보여주지 않고,
웹페이지를 따로 호출해서, html 받아오고,
그 스트링을 UIWebView 에 넣는 방법.
왜 이렇게 했냐하면, 웹페이지 로딩 진행바를 화면에 표시해 주기 위해서였다.
근데, 실제로 해보니까,
html 스트링 자체는 크기가 별로 안커서, 서버에서 금방 받아오는데
html 안에 들어있는, 이미지등 다른 요소들의 로딩시간이 더 많이 걸려서
별로 효과가 좋지는 않다.
html 스트링을 읽어오는 동안은 진행바가 표시되는데...
그 시간은 짧아서, 진행바가 금방 100% 까지 차고,
그 이후에, 실제 이미지들을 로딩하니까,
진행바가 100% 까지 가서, 한동안 그대로 있다가,
웹 페이지가 보여지게 된다.
//******************************************************************************
// LibWeb.h
//******************************************************************************
#import <Foundation/Foundation.h>
#import "LibProtocol.h"
#define WINGLISH_URL_BASE @"http://xxx/"
#define WINGLISH_URL_LOGIN @"http://xxxxx"
#define WINGLISH_URL_TEACHER @"http://xxxxxx"
#define WINGLISH_URL_LEVELTEST @"http://xxxxxxx"
#define WINGLISH_URL_SCHEDULE @"http://xxxxxxxxxx"
#define WINGLISH_URL_MYINFO @"http://xxxxxxxx"
#define WINGLISH_URL_REPORT @"http://xxxxxxxxxxxxxxx"
@interface LibWeb : NSObject
{
@private
int iHTMLFlag;
NSMutableData* dataHTML;
long long iTotalReceiveByte;
//NSURLRequest* urlRequest;
NSMutableURLRequest* urlRequest;
@public
NSString* sHTML;
id <LibProtocolWeb> libProtocolWeb;
}
- (id)initWithURL:(NSString*)sURL withHTMLFlag:(int)i;
@end
//******************************************************************************
// LibWeb.m
//******************************************************************************
#import "LibWeb.h"
static NSArray* aryCookies;
@implementation LibWeb
- (id)initWithURL:(NSString*)sURL withHTMLFlag:(int)i
{
self = [super init];
if(self == nil) return self;
iHTMLFlag = i;
dataHTML = [[NSMutableData alloc] init];
urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:sURL]];
NSURLConnection* urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
[urlConnection release];
return self;
}
#pragma mark - NSURLConnectionDelegate Methods
//------------------------------------------------------------------------------
// 서버 접속 시작
//------------------------------------------------------------------------------
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
[libProtocolWeb webDataReceiveStart];
return request;
}
//------------------------------------------------------------------------------
// 헤더를 다 받았을때...
//------------------------------------------------------------------------------
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
long long iContentLength = [response expectedContentLength];
NSLog(@"iContentLength=[%lld]", iContentLength);
// chunked 일때는, 전체 크기를 알수 없다. 그래서 대충 큰 값으로 셋팅함.
if(iContentLength == NSURLResponseUnknownLength) iContentLength = 999999;
if([libProtocolWeb respondsToSelector:@selector(webSetContentLength:)])
[libProtocolWeb webSetContentLength:iContentLength];
}
//------------------------------------------------------------------------------
// 데이타 받는중...
//------------------------------------------------------------------------------
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"webDataReceiving");
[dataHTML appendBytes:data.bytes length:data.length];
//NSLog(@"dataHTML.length=[%u]", dataHTML.length);
//NSLog(@"data=[%@]", data);
NSString* s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"s=[%@]", s);
if([libProtocolWeb respondsToSelector:@selector(webDataReceiving:)])
[libProtocolWeb webDataReceiving:dataHTML.length];
}
//------------------------------------------------------------------------------
// 데이타 다 받았을때...
//------------------------------------------------------------------------------
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
iTotalReceiveByte = dataHTML.length;
// 받은데이타를 모두 문자열로 바꾼다.
//sHTML = [[NSString alloc] initWithData:dataHTML encoding:NSUTF8StringEncoding]; // utf-8
//sHTML = [[NSString alloc] initWithData:dataHTML encoding:-2147481280]; // euc-kr
NSString* sURL = [[urlRequest URL] absoluteString];
if([sURL isEqualToString:WINGLISH_URL_TEACHER])
sHTML = [[NSString alloc] initWithData:dataHTML encoding:-2147481280]; // euc-kr
else
sHTML = [[NSString alloc] initWithData:dataHTML encoding:NSUTF8StringEncoding]; // utf-8
NSLog(@"iTotalReceiveByte = [%lld]", iTotalReceiveByte);
//NSLog(@"sHTML = [%@]", sHTML);
[libProtocolWeb webDataReceiveDone:true flag:iHTMLFlag iTotalBytes:iTotalReceiveByte];
}
//------------------------------------------------------------------------------
// 에러났을때...
//------------------------------------------------------------------------------
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" message:@"데이타 수신중 에러 발생 !" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
//------------------------------------------------------------------------------
// 로그인페이지를 호출했을때, 로그인 결과값 검사
//------------------------------------------------------------------------------
- (bool)checkWinglishLoginResult
{
NSLog(@"checkWinglishLoginResult=[%@]", [sHTML substringToIndex:1]);
// 로그인 실패
if(![[sHTML substringToIndex:1] isEqualToString:@"Y"])
{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" message:@"로그인 실패 !\nID 또는 Password 가 잘못되었습니다" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return false;
}
/*
// 로그인 성공. 쿠키값을 static 변수에 저장함.
aryCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
// 생성된 쿠키 찍어봄
NSLog(@"-------------------------------");
NSHTTPCookie *cookie;
for (cookie in aryCookies)
{
NSLog(@"cookie.name=[%@] cookie.value=[%@]", cookie.name, cookie.value);
}
NSLog(@"-------------------------------");
*/
return true;
}
- (void)dealloc
{
[urlRequest release];
[dataHTML release];
[sHTML release];
[super dealloc];
}
@end
//******************************************************************************
// TeacherView.h
//******************************************************************************
LibWeb* libWeb;
UIWebView* wvMain;
NSMutableArray* aryHTMLPage;
int iTotalContentLength;
UILabel* lblWaitingMessage;
UIProgressView* pvWaiting;
//******************************************************************************
// TeacherView.m
//******************************************************************************
//------------------------------------------------------------------------------
// 초기화
//------------------------------------------------------------------------------
- (id)initWithFrame:(CGRect)frame
{
// webview
wvMain = [[UIWebView alloc] initWithFrame:CGRectMake(frame.origin.x, 38.0, frame.size.width, 374.0)];
wvMain.backgroundColor = [UIColor clearColor];
wvMain.delegate = self;
wvMain.dataDetectorTypes = UIDataDetectorTypeNone;
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:WINGLISH_URL_TEACHER]];
[wvMain loadRequest:request];
[self addSubview:wvMain];
[self requestWebPage:WINGLISH_URL_TEACHER];
return self;
}
//------------------------------------------------------------------------------
// 웹페이지 호출
//------------------------------------------------------------------------------
- (void)requestWebPage:(NSString*)sURL
{
if(libWeb != nil)
{
[libWeb release];
libWeb = nil;
}
libWeb = [[LibWeb alloc] initWithURL:sURL withHTMLFlag:1];
libWeb->libProtocolWeb = self;
}
//------------------------------------------------------------------------------
// HTML 문자열을 webview에 보여주기
//------------------------------------------------------------------------------
- (void)showHTMLPage:(NSString*)sHTML withSaveOption:(bool)b
{
if(b) [aryHTMLPage addObject:sHTML];
[wvMain loadHTMLString:sHTML baseURL:[NSURL URLWithString:WINGLISH_URL_BASE]];
NSLog(@"aryHTMLPage.count = [%d]", aryHTMLPage.count);
if(aryHTMLPage.count > 1)
btnBack.alpha = 1.0;
else
btnBack.alpha = 0.0;
}
//------------------------------------------------------------------------------
// Back 버튼
//------------------------------------------------------------------------------
- (void)goBack:(UIButton*)btn
{
[aryHTMLPage removeLastObject];
NSString* sHTML = [aryHTMLPage lastObject];
[self showHTMLPage:sHTML withSaveOption:false];
}
//------------------------------------------------------------------------------
// 웹페이지 로딩 진행바 보여주기
//------------------------------------------------------------------------------
- (void)progressShow:(float)iProgress
{
if(lblWaitingMessage == nil)
{
lblWaitingMessage = [[UILabel alloc] initWithFrame:CGRectMake(LibDeviceInfo.SCREEN_WIDTH/2-LibDeviceInfo.SCREEN_WIDTH/4, LibDeviceInfo.SCREEN_HEIGHT/2-90.0, LibDeviceInfo.SCREEN_WIDTH/2, 120.0)];
lblWaitingMessage.layer.cornerRadius = 15.0;
lblWaitingMessage.layer.masksToBounds = YES;
lblWaitingMessage.layer.borderColor = [UIColor lightGrayColor].CGColor;
lblWaitingMessage.layer.borderWidth = 1.5;
lblWaitingMessage.backgroundColor = [UIColor blueColor];
lblWaitingMessage.alpha = 0.5;
lblWaitingMessage.text = @"loading...";
lblWaitingMessage.textColor = [UIColor whiteColor];
lblWaitingMessage.textAlignment = UITextAlignmentCenter;
lblWaitingMessage.font = [UIFont boldSystemFontOfSize:14.0];
[self addSubview:lblWaitingMessage];
pvWaiting = [[UIProgressView alloc] initWithFrame:CGRectMake(5.0, 40.0, lblWaitingMessage.frame.size.width-10.0, 10.0)];
[lblWaitingMessage addSubview:pvWaiting];
}
//NSLog(@"iProgress=[%f]", [iProgress floatValue]);
[pvWaiting setProgress:iProgress];
float iAISize = 30;
CGRect frame = CGRectMake(LibDeviceInfo.SCREEN_WIDTH/2-(iAISize/2), LibDeviceInfo.SCREEN_HEIGHT/2-(iAISize/2), iAISize, iAISize);
[LibCommon activityIndicatorShow:frame withOwnerView:self];
}
//------------------------------------------------------------------------------
// 웹페이지 로딩 진행바 숨기기
//------------------------------------------------------------------------------
- (void)progressHide
{
if(pvWaiting != nil)
{
[pvWaiting removeFromSuperview];
[pvWaiting release];
pvWaiting = nil;
}
if(lblWaitingMessage != nil)
{
[lblWaitingMessage removeFromSuperview];
[lblWaitingMessage release];
lblWaitingMessage = nil;
}
[LibCommon activityIndicatorHide];
}
#pragma mark - UIWebViewDelegate Methods
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString* sRequestURL = [[request URL] absoluteString];
NSLog(@"url=[%@] navigationType=[%d]", sRequestURL, navigationType);
if([sRequestURL isEqualToString:WINGLISH_URL_BASE]) return YES;
[self requestWebPage:sRequestURL];
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
NSLog(@"webViewDelegate webViewDidStartLoad");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(@"webViewDelegate webViewDidFinishLoad");
[self progressHide];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(@"webViewDelegate didFailLoadWithError");
[self progressHide];
}
#pragma mark - LibProtocolWeb Methods
//------------------------------------------------------------------------------
// 데이타 받기 시작할때
//------------------------------------------------------------------------------
- (void)webDataReceiveStart
{
NSLog(@"webDataReceiveStart");
[self progressShow:0.0];
}
//------------------------------------------------------------------------------
// 데이타의 헤더를 다 받아서, 전체 Content Length 를 알아냈을때
//------------------------------------------------------------------------------
- (void)webSetContentLength:(long long)iContentLength
{
iTotalContentLength = iContentLength;
}
//------------------------------------------------------------------------------
// 데이타를 받고있는 중일때
//------------------------------------------------------------------------------
- (void)webDataReceiving:(long long)iReceivedBytes
{
float iDownloadRate = iReceivedBytes / iTotalContentLength * 100;
if(iDownloadRate >= 100.0) iDownloadRate = 100.0;
[self progressShow:iDownloadRate];
}
//------------------------------------------------------------------------------
// 데이타를 다 받았을때
//------------------------------------------------------------------------------
- (void)webDataReceiveDone:(bool)bOK flag:(int)iFlag iTotalBytes:(long long)iTotalBytes
{
NSLog(@"webDataReceiveDone");
[self showHTMLPage:libWeb->sHTML withSaveOption:true];
}
반응형
'iOS 초보' 카테고리의 다른 글
ios 화면크기, 해상도 (0) | 2014.07.02 |
---|---|
xcode, debuging tab (0) | 2014.07.02 |
맥. proxy 서버 사용하기 (0) | 2014.07.02 |
맥, boost (0) | 2014.07.02 |
audio session. 스피커 제어하기 (0) | 2014.07.02 |