Привет, я сталкиваюсь с проблемой при преобразовании NSData
в NSDictionary
с использованием NSJSONSerialization
?Как преобразовать NSData в NSDictionary с помощью NSJSONSerialization?
Я получил данные, используя свой код, но не смог его преобразовать в json.
Вот мой код ...
ViewController.h Файл
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<NSURLConnectionDelegate>
{
NSString *massage;
NSURL *url;
NSMutableURLRequest *request;
NSURLConnection *connection;
NSMutableData *httpbody;
NSMutableData *webData;
NSData *responceData;
NSDictionary *responceJson;
}
и ViewController.m Файл
#import "ViewController.h"
@interface ViewController()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *mobile = @"123456789";
NSString *password = @"Welcome123";
NSString *deviceId = @"123sdfg15641ert321ret";
url = [NSURL URLWithString:@"http://203.109.87.34:8585/d-cab/web/app_dev.php/api/v1"];
massage = [NSString stringWithFormat:@"{\"action\":\"login\",\"data\":{\"contact\":\"%@\",\"password\":\"%@\",\"deviceId\":\"%@\"}}",mobile,password,deviceId];
//NSLog(@"Body = %@", massage);
httpbody = [ NSMutableData dataWithBytes: [ massage UTF8String ] length: [ massage length ] ];
request = [NSMutableURLRequest requestWithURL: url];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: httpbody];
[request setTimeoutInterval:10.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
//[connection start];
if (connection) {
webData = [[NSMutableData alloc]init];
}
}
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[webData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
//NSLog(@"WebData = %@",webData);
//NSLog(@"=================================");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError* error = nil;
responceJson = [NSJSONSerialization JSONObjectWithData:webData options:kNilOptions error:&error];
NSLog(@"ResponceJSON = %@",responceJson);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Show error message
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error In connection" message:@"We are facing some problem in connection. Please Check your Internet Connection." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
Пожалуйста Проверьте свой код и скажите мне, где и какое изменение я должен сделать?
Наконец-то вы получили решение, хорошее –