Thursday, September 22, 2016

NSURLSession Web service call in Objective c


Web service call in NSURLSession:

    NSString *URLString = [NSString stringWithFormat:@"Your URL"];
    //create a url object
    NSURL *url = [NSURL URLWithString:URLString];
    //create a configuration object for the session object
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    //start a new session with our previously created configuration
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    //    / 2
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    request.HTTPMethod = @"POST";
    
    //Parameter dictionary.
    NSDictionary *dictionary = @{@"DeviceUDID": @"836475-2C6E-4081-A04E-45689234682"};
    NSError *error = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary
                                                   options:kNilOptions error:&error];
    if (!error)
    {
        NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data,NSURLResponse *response,NSError *error)
        {
            // Handle response here
            if(error != nil)
            {
                NSLog(@"Error : %@", [error localizedDescription]);
            }
            else
            {
                NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"Result : %@", responseString);
            }
        }];
        [uploadTask resume];

    }

No comments:

Post a Comment