메뉴 건너뛰기

app

[xcode] NSMutableURLRequest POST전송과 결과 XML 출력(파싱포함)

박영식2010.09.08 01:24조회 수 11572댓글 2

    • 글자 크기

[h파일]

typedef enum {

etNone = 0,

etItem

} eElementType;


@interface 이름ViewController : UIViewController {

NSMutableData *receiveData;

eElementType elementType;

NSMutableArray *xmlParseData;

NSMutableString *xmlValue;

}

[m파일]


-(IBAction)buttonPressed:(id)sender

{

NSDate *now = [NSDate date];

NSString *bodyString = [[NSString alloc] initWithFormat:@"date=%@",now];

NSString *url=@"http://address/test.php"; //xml address

// URL 접속 초기화

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] 

cachePolicy:NSURLRequestUseProtocolCachePolicy 

timeoutInterval:15.0]; 

 

[request setHTTPMethod:@"POST"]; // POST 선언하고

[request setHTTPBody:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];

 

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

if (connection) { 

xmlParseData = [[NSMutableArray alloc] init];

xmlValue = [[NSMutableString alloc] init];

receiveData = [[NSMutableData data] retain]; // 수신할 데이터를 받을 공간을 마련

NSLog(@"success con");

}

NSString *stitle = [[NSString alloc] initWithFormat:@"%@ 등록확인",sname.text];

NSString *message = [[NSString alloc] initWithFormat:@"등록되었습니다."];

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:stitle message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

[alert show];

[alert release];

[stitle release];

[message release];

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

[receiveData appendData:data];

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

NSString *data;

data = [[NSString alloc] initWithData:receiveData encoding:NSUTF8StringEncoding];

NSLog(data); NSXMLParser *parser = [[NSXMLParser alloc] initWithData:receiveData];

    [parser setDelegate:self];

    [parser parse];

[parser release];

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

[receiveData release];

}


#pragma mark XMLParse delegate methods


- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

if ([elementName isEqualToString:@"Item"])  // 최상위 노드이름;

elementType = etItem;

// NSLog(@"parsing part start");

[xmlValue setString:@""];

}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

NSString *msg=@"";

//NSLog(@"parsing part");

if (elementType != etItem)

return;

if ([elementName isEqualToString:@"Title"]) {

msg = [ [ NSString alloc ] initWithFormat:@"i= %@" , [NSString stringWithString:xmlValue]];

NSLog(msg);

} else if ([elementName isEqualToString:@"Image"]) {

}

}



- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {

if (elementType == etItem) {

[xmlValue appendString:string];

}

}

박영식 (비회원)
    • 글자 크기
[C++] 하위 폴더 검색 최간편 소스 (by 박영식) [아이폰] 아이폰 앱 스토어 리뷰 가이드 라인 (by suritam9)

댓글 달기

댓글 2
  • 글쓴지 오래되신거알지만..질문이 생겨서여..웹에 관한 지식이 전무한상태로..HTML파싱을 하려니깐..

    너무 막혀서여; 로그인 후 파싱을 하려하는데... 로그인 정보는 어떻게 전달하는건가여..?

    너무 막연한 질문이다 싶으시면..어디를 공부하라고만 말씀해주심안될까여;;?
  • 윤하늘님께
    해당 페이지의 로그인 방식 때문에 힘들거라 생각되지만, 적어 봅니다.

    NSString *bodyString = [[NSString alloc] initWithFormat:@"date=%@",now];

    코드 중에 bodyString이 post로 전송되는 parameter를 기술하는 부분입니다.
    NSString *bodyString = [[NSString alloc] initWithFormat:@"id=%@&pw=%@",id,pw];

    으로 전송하면, server에서 $_POST['id'] $_POST['pw'] 로 동작한다고 가정할 때, id와 pw를 전송할 수 있습니다.
    그런데, 로그인 후에, 리턴 url로 리다이렉션 된다면, 이런 방식으로는 웹페이지를 크롤링 할 수 없겠죠.
    xml을 엑세스 할 때 로그인 정보를 parameter가 필요하다면 예시대로 하실 수 있습니다.

    문제가 없다면, html도 xml파서로 파싱할 수 있겠군요.

    좀 더 고급으로 로그인 세션을 갖고 페이지를 접근하시려면, PHP의 snoopy 라이브러리로 세션값을 설정해서 접근하는 법을 찾아보시기 바랍니다. 자동화된 코드로 php가 인증을 통해 얻은 파일을 리턴해서, xcode에서 파싱 가능한 html을 얻을 수 있을 거라고 생각합니다.
박영식
2003.11.05 조회 17485
박영식
2008.07.23 조회 7760
suritam9
2013.08.23 조회 7110
lispro06
2016.11.01 조회 7074
이전 1 2 3 4 5 6 7 8 9 10... 14다음
첨부 (0)
위로