最近在研究iOS開發,對於Http連線的好處
在這裡就不再贅述

之前寫過Android版本的,請見:

http://j796160836.pixnet.net/blog/post/28994669

 

雖然我也在學習中,我盡量解釋其方法
如果有誤,還煩請大大們指正

-------------------------------------------------------------------------------------------------------------------

 

開一個新的專案

在Interface Builder版面設計中,拉出一個Button和一個Label

-------------------------------------------------------------------------------------------------------------------

其中 Button Touch Up Instide 中綁定  - (IBAction)request_btn_onclick:(id)sender   方法

LabelReferencing Outlets 綁定  @property (retain, nonatomic) IBOutletUILabel *label;     變數

-------------------------------------------------------------------------------------------------------------------

 

ViewController.h 放入以下宣告

@interface ViewController : UIViewController

{

    NSMutableData *responseData;

}

 

// 開始接收資料,會呼叫此方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

// 接收新的資料時,會呼叫此方法

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

// 下載完畢時,會呼叫此方法

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

// 連線錯誤時,會呼叫此方法

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;

-------------------------------------------------------------------------------------------------------------------

ViewController.m 加入以下程式片段

 

#pragma mark - Connection delegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    // 開始下載,重置responseData資料

    NSLog(@"didReceiveResponse");

    [responseDatasetLength:0];

}

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

{

    // 下載中,附加資料

    [responseDataappendData:data];

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    // 下載完成,釋放responseData

    [connection release];

    NSLog (@"succeeded  %d byte received", [responseDatalength]);

    // 轉譯編碼文字

    NSString *responseString = [[NSStringalloc] initWithData:responseDataencoding:NSUTF8StringEncoding];

   

    [responseDatarelease];

   

    label.text =  responseString;

    [responseString release];

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    // 下載錯誤

    label.text = [NSStringstringWithFormat:@"Connection failed: %@",[error description]];

    NSLog(@"Connection failed! Error - %@ %@",

          [error localizedDescription],

          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);

}

-------------------------------------------------------------------------------------------------------------------

這段就是按鈕按下去會執行的語法

#pragma mark – Button onClick

 

- (IBAction)request_btn_onclick:(id)sender {

   

    responseData = [[NSMutableDatadata] retain];

    NSString *url = [NSString stringWithFormat:@"http://127.0.0.1/httptest/t.php"];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURLURLWithString:url ]];

    [[NSURLConnection alloc] initWithRequest:request delegate:self];

   

}

-------------------------------------------------------------------------------------------------------------------

我簡單解釋一下

剛剛在ViewController之中新增一個 NSMutableDatadata 變數 (Mutable代表可變動的)

然後在 - (IBAction)request_btn_onclick:(id)sender 這裡

指定一個 url 就是我們要瀏覽的位置,GET要上傳的內容就串在後面

再來建立一個 NSURLRequest 和 NSURLConnection 把連線建立起來

回應的部分傳進delegate (委派)之中

 

而delegate (委派)有四個

 

// 開始接收資料,會呼叫此方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

當系統開始要接收資料的時候這個方法會被呼叫到
要把這 responseData 給清空,如果UI上有ProgressBar的話要將之歸零

// 接收新的資料時,會呼叫此方法

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

每次資料在下載的時候,會不停的呼叫這個方法
可以看到這個data傳入的參數,就是每一小塊一小塊的資料
我們只要把它累加起來即可,如果UI上有ProgressBar的話就可以慢慢累加1

// 下載完畢時,會呼叫此方法

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

最後跑完會呼叫這個方法,就是你需要做處理的部分
例如顯示到畫面上,存入SQLite....等等


// 連線錯誤時,會呼叫此方法

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;

最後就是這個,中間若有網路錯誤等因素就會呼叫這個方法
你可以跳一個提示框或是印Log

 

這個範例的url是指到本機的Apache Server的其中的一隻php網頁
你也可以換成yahoo等網站,只是會跑出一堆網頁原始碼而已

可以玩看看 

-------------------------------------------------------------------------------------------------------------------

以下是我不負責任的把語法翻成大家熟悉的Java
對於像我一樣,對Objective-C有閱讀障礙的

可以看一下(當然,底下的程式完全不能跑,就不用複製了....XD)

 

public  class  ViewController  implements  NSURLConnectionDelegate  {

 

   public  static  UILabel  label;

 

   private  NSMutableData  responseData;

 

   public  void  viewDidLoad()  {

 

      responseData  =  new  NSMutableData();

 

      NSString  url  =  "http://127.0.0.1/httptest/t.php";

 

      NSURLRequest  request  =  new  NSURLRequest(url);

 

      new  NSURLConnection(request,  this);

 

   }

 

 

 

   @Override

 

   public  void  didReceiveResponse(NSURLConnection  connection, NSURLResponse  response)  {

 

      //  開始下載,重置responseData資料

 

      NSLog("didReceiveResponse");

 

      responseData.setLength(0);

 

   }

 

 

 

   @Override

 

   public  void  didReceiveData(NSURLConnection  connection,  NSData  data)  {

 

      //  下載中,附加資料

 

      responseData.appendData(data);

 

   }

 

 

 

   @Override

 

   public  void  connectionDidFinishLoading(NSURLConnection  connection)  {

 

      //  下載完成,釋放responseData

 

      connection  =  null;

 

      NSLog(NSString.format("succeeded    %d  byte  received"responseData.length));

 

      //  轉譯編碼文字

 

      NSString  responseNSString  =  responseData.toNSStringWithEncoding(NSUTF8NSStringEncoding);

 

      responseData  =  null;

 

 

 

      label.text  =  responseNSString;

 

      responseNSString  =  null;

 

   }

 

 

 

   @Override

 

   public  void  didFailWithError(NSURLConnection  connection,  NSError  error)  {

 

      //  下載錯誤

 

      label.text  =  NSString.format("Connection  failed:  %s",  error.description());

 

      NSLog(NSString.format("Connection  failed!  Error  -  %s",

 

             error.localizedDescription()));

 

   }

 

}

-------------------------------------------------------------------------------------------------------------------

參考資料

http://www.01-labor.com/2011/07/nsurlconnectionhttp.html

http://stm237.iteye.com/blog/1005752

NSURLConnection官方文件

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html

arrow
arrow
    全站熱搜

    Johnny 鋼鍊 發表在 痞客邦 留言(0) 人氣()