陈斌彬的技术博客

Stay foolish,stay hungry

网络请求模块模板

h文件

#import <Foundation/Foundation.h>

@interface BBYuYueGuaHaoShowRequestManager : NSObject

@property (nonatomic, strong) NSURLConnection *informationMenuConn;//请求菜单列表
@property (nonatomic, strong) NSMutableData *receiveDataInformationList;//服务器返回的information列表数据

- (void)setupRequest:(NSString *)speciality_code;

@end

m文件

//
//  BBYuYueGuaHaoShowRequestManager.m
//  HangyuHealth
//
//  Created by WuYongmin on 16/4/19.
//  Copyright © 2016年 AntWork. All rights reserved.
//

#import "BBYuYueGuaHaoShowRequestManager.h"

@implementation BBYuYueGuaHaoShowRequestManager

- (void)initData {



}

- (void)setupRequest:(NSString *)speciality_code {

    [self initData];
    UserDataCenter *udc =[UserDataCenter sharedInstance];
    NSString *access_token = udc.userInfo.strAccessToken;
    NSString *urlString = [NSString stringWithFormat:@"http://112.91.128.50:9081/dpim/webapi/hospital/get-schedule-info?access_token=%@&speciality_code=%@",access_token,speciality_code];
    // 初始化一个NSURL对象
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    // 设置请求方法,可以省略,默认就是GET请求
    request.HTTPMethod = @"GET";
    // 如果60秒过后服务器还没有相应,就算请求超时
    request.timeoutInterval = 60;
    // 初始化一个连接
    self.informationMenuConn = [NSURLConnection connectionWithRequest:request delegate:self];
    // 开始一个异步请求
    [self.informationMenuConn start];
}


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

    if (self.informationMenuConn==connection) {

        self.receiveDataInformationList = [NSMutableData data];
    }
}

#pragma mark - 接收到服务器返回的数据时调用(如果数据比较多,这个方法可能会被调用多次)

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

    // 拼接数据
    if(self.informationMenuConn==connection) {

        [self.receiveDataInformationList appendData:data];
    }

}

#pragma mark - 网络连接出错时调用

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

    NSLog(@"网络连接出错:%@", [error localizedDescription]);
}


#pragma mark - 服务器的数据已经接收完毕时调用

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

}

@end