2011-03-27

[iOS] 웹페이지 긁어오기

이번엔 iOS SDK 기반 Objective-C에서도 웹페이지를 비동기로 긁어오는 기능을 하는 코드를 메모해본다. (NS 계열 API이니 아이폰/아이패드/Mac OS X에서 다 쓸 수 있을 듯)

사용하는 클래스는 NSURLRequestNSURLConnection.
- (void)URLRequest:(NSString*)url {
  NSURLRequest* req =
    [NSURLRequest requestWithURL:[NSURL URLWithString:url]
                     cachePolicy:NSURLRequestUseProtocolCachePolicy
                 timeoutInterval:60];

  NSURLConnection* conn =
    [[NSURLConnection alloc]
      initWithRequest:req delegate:self];

  if (conn) {
    _recvData = [[NSMutableData data] retain];
  } else {
  // connection failed
  }
}

- (void) connection:(NSURLConnection *)connection
 didReceiveResponse:(NSURLResponse *)response {
  [_recvData setLength:0];
}

- (void) connection:(NSURLConnection *)connection
     didReceiveData:(NSData *)data {
  [_recvData appendData:data];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
  NSString* recvStr =
    [[NSString alloc]
      initWithData:_recvData
          encoding:NSUTF8StringEncoding];
  NSLog(@"Received String: %@", recvStr);

  [recvStr release];

  [connection release];
  [_recvData release];
}

- (void) connection:(NSURLConnection *)connection
   didFailWithError:(NSError *)error {
  [connection release];
  [_recvData release];
}
코드가 너무 길어질까봐 들여쓰기를 멋대로 정리해 버렸다. URLRequest 라는 메소드를 정의해서 url을 넘겨주면 나중에 데이터가 connectionDidFinishLoading 으로 들어오게 된다.

_recvData라는 멤버는 적당히 NSMutableData 로 하나 만들어 둔 것이다. 생략하긴 했지만 이런 멤버변수 관리는 원래 프로그래머가 알아서 해야 될 것이니깐.

핵심만 요약하자면

1. NSURLRequest 로 url 및 cache policy 등을 정의해서 request 객체를 만든다.

2. NSURLConnection 객체를 NSURLRequest로 생성한 객체를 이용해 만든다. 이러면 바로 request가 발송되는 듯 하다.

3. connection:didReceiveResponse가 호출되면 응답을 받기 시작하는 상황이다. 버퍼를 미리 비워두자.

4. connection:didReceiveData가 호출되면 데이터가 전송되는 상황이다. 준비해 둔 버퍼에 데이터를 붙여넣는다.

5. connectionDidFinish 를 통해 최종적으로 데이터 전송이 완료된다. 원하는 대로 데이터를 가공해서 사용하면 된다.

더 상세하게 (예를 들자면 GET 대신 POST 로 데이터를 넘겨주는 방식) 사용하려면 NSURLRequest가 아니라 NSMutableURLRequest를 이용하면 된다. setHTTPMethod 같은 메소드가 마련되어 있으니 레퍼런스 문서를 참고할 것.

댓글 12개:

  1. Hi! I'm at work surfing around your blog from my new apple iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the outstanding work!

    My web site This web page link

    답글삭제
  2. Pοst writing iѕ also a excitement, if you
    κnоw afterward you can wгіte if nоt it is complicated
    to write.

    Here is my website free
    My web page: Cccam Server How To

    답글삭제
  3. Noω I am going away to do my brеakfast,
    lateг thаn havіng my brеаkfast
    cοming oveг agаin to read further nеwѕ.


    Alѕo visit my site :: Card Sharing

    답글삭제
  4. I'm pretty pleased to uncover this great site. I need to to thank you for ones time for this particularly wonderful read!! I definitely loved every little bit of it and i also have you book marked to see new stuff on your site.

    Review my blog; cccam cccam server|server cardsharing|skybox f3 cardsharing|cccam|cardsharing anbieter|cccam pay server|cccam server premium|dreambox|server dreambox|buy cardsharing|cardsharing|cardsharing server|dreambox 800|free card sharing server|satellite cardsharing kings|test line cccam|card sharing|card sharing servers|cardsharing canalsat|cccam line|cccam test line|free cccam server|sat keys|satellite cardsharing| cccam server|server cardsharing|skybox f3 cardsharing|cccam|cardsharing anbieter|cccam pay server|cccam server premium|dreambox|server dreambox|buy cardsharing|cardsharing|cardsharing server|dreambox 800|free card sharing server|satellite cardsharing kings|test line cccam|card sharing|card sharing servers|cardsharing canalsat|cccam line|cccam test line|free cccam server|sat keys|satellite cardsharing| cccam server|server cardsharing|skybox f3 cardsharing|cccam|cardsharing anbieter|cccam pay server|cccam server premium|dreambox|server dreambox|buy cardsharing|cardsharing|cardsharing server|dreambox 800|free card sharing server|satellite cardsharing kings|test line cccam|card sharing|card sharing servers|cardsharing canalsat|cccam line|cccam test line|free cccam server|sat keys|satellite cardsharing|
    My page: satellite cardsharing kings cccam server|server cardsharing|skybox f3 cardsharing|cccam|cardsharing anbieter|cccam pay server|cccam server premium|dreambox|server dreambox|buy cardsharing|cardsharing|cardsharing server|dreambox 800|free card sharing server|satellite cardsharing kings|test line cccam|card sharing|card sharing servers|cardsharing canalsat|cccam line|cccam test line|free cccam server|sat keys|satellite cardsharing| cccam server|server cardsharing|skybox f3 cardsharing|cccam|cardsharing anbieter|cccam pay server|cccam server premium|dreambox|server dreambox|buy cardsharing|cardsharing|cardsharing server|dreambox 800|free card sharing server|satellite cardsharing kings|test line cccam|card sharing|card sharing servers|cardsharing canalsat|cccam line|cccam test line|free cccam server|sat keys|satellite cardsharing| cccam server|server cardsharing|skybox f3 cardsharing|cccam|cardsharing anbieter|cccam pay server|cccam server premium|dreambox|server dreambox|buy cardsharing|cardsharing|cardsharing server|dreambox 800|free card sharing server|satellite cardsharing kings|test line cccam|card sharing|card sharing servers|cardsharing canalsat|cccam line|cccam test line|free cccam server|sat keys|satellite cardsharing|

    답글삭제
  5. Excellent beat ! I would lіke to apprеntice while you amend yоur
    web site, hоw cοuld i subscribe for a blog ωеb sitе?
    The ассount aidеd me a аcceptable deal.
    I had bеen tiny bit аcquаіnted οf this youг broаdсast pгovіԁeԁ bright сlear idеа

    Stop by mу wеblog - http://www.lindenchamber.net/userinfo.php?uid=29152

    답글삭제
  6. Неllo thеre! Thiѕ post could not be written any betteг!
    Reading this post remіnԁs me of my οld
    гoom mate! He alwaуs kept chatting about this.
    I wіll forwaгԁ this рagе tο him.
    Pгetty sure hе wіll havе a good reаd.

    Many thanks fοr ѕharing!

    my web ѕite :: don-benjamin.co.uk

    답글삭제
  7. I’m not that muсh of а internet rеader to be hοnest but yοuг blogs really niсe,
    κеep it up! I'll go ahead and bookmark your site to come back in the future. Many thanks

    Feel free to surf to my web page - www.wk2006cam.nl

    답글삭제
  8. Greatе post. Keеp wгiting ѕuсh kind οf infο on уour ѕitе.

    Іm reallу impressed by your ѕitе.


    Ηello theгe, You've performed a great job. I'll dеfinitely ԁigg
    it and in my viеw suggeѕt tо my
    friends. I'm sure they will be benefited from this web site.

    My homepage - Cccam newcs Download

    답글삭제
  9. ӏncrеdible! This blog lοoks exactly like my old one!
    ӏt's on a entirely different topic but it has pretty much the same layout and design. Great choice of colors!

    Also visit my blog https://moodle.cad.auckland.ac.nz/user/view.php?id=11517&course=1

    답글삭제
  10. We arе a gаggle of volunteers and opening а nеω
    scheme in ouг cοmmunity. Youг websіte рroνіded us with νaluable info to worκ оn.
    You've performed an impressive task and our entire group might be grateful to you.

    Also visit my page - card sharing how to

    답글삭제
  11. Very nice article, totаlly what I ωas
    looκіng fог.

    Also visіt my sіte ... Homepage des Autors besuchen

    답글삭제
  12. Ηave you eѵer сonѕidеred сreating an e-book or
    gueѕt authοring on other ωebsites? І havе a
    blоg basеd upon on the same infoгmation yοu diѕcuss and would really lіke to havе yοu share some storieѕ/іnformatiοn.
    І knoω my visitors would apprеciаte уour work.

    If yοu arе eνen remοtelу іnterеsted, feеl free to senԁ me an email.



    my wеb blog: sponsearch.net
    my page - http://independienteaclub.com.ar/

    답글삭제