你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS_GET_網絡請求

iOS_GET_網絡請求

編輯:IOS開發綜合

同步的 get 請求

#pragma mark - 同步的 get 請求
- (IBAction)GETSynButtonDidClicked:(UIButton *)sender {

    // 1、網址裡面必須寫 http://
    NSString *urlString = @http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213;

    // 2、如果網址有漢字需要轉換(沒有漢字也可以寫)
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    // 3、根據字符串創建 url(統一資源定位符)
    NSURL *url = [NSURL URLWithString:urlString];

    // 4、根據 url 創建 request 請求類的對象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    // 5、開始去請求網絡、數據(同步) 返回data
    NSData *receiveData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    // 6、系統自帶json解析
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:receiveData options:(NSJSONReadingMutableContainers) error:nil];

    NSArray *array = dict[@news];

    self.newsArray = [NSMutableArray array];

    for (NSDictionary *smallDict in array) {
        NewsModal *modal = [[NewsModal alloc] init];
        [modal setValuesForKeysWithDictionary:smallDict];
        [self.newsArray addObject:modal];
    }

    for (NewsModal *modal in self.newsArray) {
        NSLog(@%@, modal.title);
    }
}

異步的 get 請求

#pragma mark - 異步的 get 請求
- (IBAction)GETAsyButtonDidClicked:(UIButton *)sender {

    // 1、拼接 urlString,網址裡面必須寫 http://
    NSString *urlString = @http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213;

    // 2、根據字符串創建 URL(統一資源定位符)
    NSURL *url = [NSURL URLWithString:urlString];

    // 3、根據 url 創建 request 請求類的對象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    // 4、開始去請求網絡、數據(同步) 返回data
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        // 5、系統自帶json解析
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];

        NSArray *array = dict[@news];

        self.newsArray = [NSMutableArray array];

        for (NSDictionary *smallDict in array) {
            NewsModal *modal = [[NewsModal alloc] init];
            [modal setValuesForKeysWithDictionary:smallDict];
            [self.newsArray addObject:modal];
        }

        for (NewsModal *modal in self.newsArray) {
            NSLog(@%@, modal.title);
        }

    }];
}

 

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved