如何将数据发送到服务器并在同一个方法中接收响应

时间:2016-12-26 10:22:18

标签: ios objective-c

我是ios的新手我怀疑我想将数据发送到服务器并以相同的方法接收响应

我有一个班级名字 profile.m我希望将数据发送到服务类并在配置文件类中接收响应

Profile.m:

NSString *parameter = [NSString stringWithFormat:@"%@&access_token=%@&lksite=social&lkmenu=profile&lktype=view&displayedname=%@&displayid=%@", baseUrl, accessToken, userName,userId];

Service *service = [[Service alloc]init];
   [service sendDataToServer:@"POST" andUrl:parameter andUrl:baseUrl];

Service.m

-(void) sendDataToServer:(NSString *) method andUrl:(NSString *) getUrl andUrl:(NSString *)baseUrl{
NSMutableData *jsondata;
Session *ses =[[Session alloc]init];
accessToken = [ses getAccessToken];
NSLog(@"Access Token---> %@",accessToken);

NSString *baseUrl1 = [NSString baseUrl];


if([method isEqualToString:@"GET"]){
    NSString *urlStr = [NSString stringWithFormat: @"%@&access_token=%@",getUrl,accessToken];
    url = [NSURL URLWithString: urlStr];
    urlRequest=  [NSMutableURLRequest requestWithURL:url];
    urlRequest.HTTPMethod=method;
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    if( connection )
    {
        urlMutable = [NSMutableData new];
    }
}else{
    NSData *parameterData = [getUrl dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    url = [NSURL URLWithString: baseUrl1];
    urlRequest=[NSMutableURLRequest requestWithURL:url];
    urlRequest.HTTPBody=parameterData;
    urlRequest.HTTPMethod=method;
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    if( connection )
    {
        urlMutable = [NSMutableData new];
    }
}}

2 个答案:

答案 0 :(得分:1)

您可以使用NSLocalNotification来完成任务。 使用NSLocalNotification有三个简单的步骤。

1)为此,您可以在Profile.m文件中将代码编写为:

- (void)viewDidLoad {
    [super viewDidLoad];

Service *Service = [[Service alloc] init];
        [Service sendDataToServer:(with your parameters here)];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(responceMethod:) name:@"WebServiceCall" object:nil];
}

2)在您的Service.m类中进行服务调用

    -(void) sendDataToServer:(NSString *) method andUrl:(NSString *) getUrl andUrl:(NSString *)baseUrl{
    NSMutableData *jsondata;
    Session *ses =[[Session alloc]init];
    accessToken = [ses getAccessToken];
    NSLog(@"Access Token---> %@",accessToken);

    NSString *baseUrl1 = [NSString baseUrl];


    if([method isEqualToString:@"GET"]){
        NSString *urlStr = [NSString stringWithFormat: @"%@&access_token=%@",getUrl,accessToken];
        url = [NSURL URLWithString: urlStr];
        urlRequest=  [NSMutableURLRequest requestWithURL:url];
        urlRequest.HTTPMethod=method;
        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
        if( connection )
        {
            urlMutable = [NSMutableData new];
        }
    }else{
        NSData *parameterData = [getUrl dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        url = [NSURL URLWithString: baseUrl1];
        urlRequest=[NSMutableURLRequest requestWithURL:url];
        urlRequest.HTTPBody=parameterData;
        urlRequest.HTTPMethod=method;
        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
        if( connection )
        {
            urlMutable = [NSMutableData new];
        }
    }

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
    int errorCode = (int)httpResponse.statusCode;
    NSLog(@"response is %d", errorCode);

    [urlMutable setLength: 0];
}

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

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSError *error;
    id *response = [NSJSONSerialization JSONObjectWithData:webData options:NSJSONReadingAllowFragments error:&error];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"WebServiceCall" object:nil userInfo:response];
}

最后是 3)在您在Profile.m文件中编写的方法中实现您的响应解析,如:

-(void)responceMethod:(NSNotification *)notif{
NSDictionary *dict = [notif userInfo];
// Your response parsing.
}

答案 1 :(得分:-1)

将块声明为:

typedef void (^completionBlock)(id responseObject , NSError *error);

然后将此块添加到您的方法中:

- (void) performRequestWithCompletion:(completionBlock)block;

在调用此方法时,将返回“responseObject”和“error”。成功时错误为零