通常,为了下载JSON,我使用AFNetworking创建一个带有此代码的单例
- (void)getJSON {
NSURLRequest * request =
[NSURLRequest requestWithURL:
[NSURL URLWithString:@"http://URL"]];
AFJSONRequestOperation * operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSArray * js = JSON;
[_delegate dati:js];
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * filePath = [[paths lastObject] stringByAppendingPathComponent:@"downloaded.json"];
NSData * data = [NSJSONSerialization dataWithJSONObject:JSON
options:NSJSONWritingPrettyPrinted
error:NULL];
[data writeToFile:filePath
atomically:YES];
}];
[operation start];
}
并在View Controller中调用此代码
[[DataManager sharedClass] getJSON];
并且它可以工作,但现在我需要将一些参数(作为授权代码,GPS坐标,用户的邮件或类似的东西)发送(发送)到服务器的请求中以接收特定的JSON。服务器已经配置,它工作正常,但我找不到修改我的代码来做到这一点的指南。有人知道怎么办吗?
答案 0 :(得分:0)
这是使用JSON将数据发布到服务器的示例,例如json如下:
NSDictionary *json = @{@"authorization_code": yourAuthorizationCode,@"gps": @{@"lat": latitude,@"lng": longitude},@"email":email};
在服务器上发布也取决于您的服务器要求,因此如果需要发布JSON,则可以这样:
//Create an AFHTTPRequestOperationManager
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//Depending if you need a HTTP header, you create one
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSString *yourAuthorizationCode;
NSString *latitude;
NSString *longitude;
NSString *email;
//My data to be posted via JSON
NSDictionary *json = @{@"authorization_code": yourAuthorizationCode,@"gps": @{@"lat": latitude,@"lng": longitude},@"email":email};
//Sending Post Method, with parameter JSON
[manager POST:@"http://myphp.com/api/v1/profile" parameters:json success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"JSON: %@", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"Error at creating post: %@", error);
}];
在此方法中,参数在URL中传递,并以URL格式将其发布到服务器
//Create an AFHTTPRequestOperationManager
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *yourAuthorizationCode;
NSString *latitude;
NSString *longitude;
NSString *email;
//Sending Post Method, with parameter JSON (You can change your method of sending data to server just by replacing POST with GET)
[manager POST:[NSString stringWithFormat:@"http://myphp.com/api/v1/profile?authorization_code=%@&gps_lat=%@&gps_lng=%@&email=%@",yourAuthorizationCode,latitude,longitude,email] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"JSON: %@", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"Error at creating post: %@", error);
}];
希望它有所帮助,给我反馈!