преобразовать координаты в JSON для загрузки в базу данных

Я пытаюсь преобразовать местоположение пользователя в json, прежде чем я смогу вставить его в базу данных mysql с помощью php, кто-нибудь может помочь? Я очень новичок в этом, мой код ниже:

Детали проекта: я пытаюсь создать код, который будет:

  • при первом запуске создайте ID пользователя
  • собрать местоположение устройства
  • преобразовать идентификатор пользователя и долготу / широту в Json
  • распечатать Json на этикетке «Label1»
  • затем отправьте JSON в базу данных MySQL

Прямо сейчас на моем ярлыке не отображаются координаты или идентификатор пользователя, кто-нибудь может помочь?

Это мой ViewController.m

#import "ViewController.h"
@interface ViewController ()
{
CLLocationManager *locationManager;
}
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.mapView.delegate = self;

locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];

[locationManager startUpdatingLocation];
NSLog(@" lat: %f",locationManager.location.coordinate.latitude);
NSLog(@" lon: %f",locationManager.location.coordinate.longitude);

//   Request use on iOS 8
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
[self.mapView setShowsUserLocation:YES];
} else {
[locationManager requestWhenInUseAuthorization];
}if ([[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedOnce"])
{
//App has previously launched
}
else
{
//First launch
NSString *identifierString = [[NSUUID UUID] UUIDString];
[[NSUserDefaults standardUserDefaults] setObject:identifierString forKey:@"uuidKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
}

NSURL *jsonFileUrl = [NSURL URLWithString:@"http://random.name/service.php"];
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
[NSURLConnection connectionWithRequest:urlRequest delegate:self];

}

#pragma mark NSURLConnectionDataProtocol Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
_downloadedData = [[NSMutableData alloc] init];
}

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSMutableArray *_locations = [[NSMutableArray alloc] init];

// Parse the JSON that came in
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];

CLLocationCoordinate2D coordinate;
// Loop through Json objects, create question objects and add them to our questions array
for (int i = 0; i < jsonArray.count; i++)
{
NSDictionary *jsonElement = jsonArray[i];
MKPointAnnotation* marker = [[MKPointAnnotation alloc] init];

marker.title = jsonElement[@"Name"];
marker.subtitle = jsonElement[@"Address"];
coordinate.latitude = [jsonElement [@"Latitude"] doubleValue];
coordinate.longitude = [jsonElement [@"Longitude"] doubleValue];

marker.coordinate = coordinate;
// Add this question to the locations array
[_locations addObject:marker];

NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:
[jsonElement objectForKey:@"Name"], @"uuidKey",
[jsonElement objectForKey:@"Latitude"], @" lat: %f",
[jsonElement objectForKey:@"Longitude"], @"lon: %f",
nil];

//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:info
options:NSJSONWritingPrettyPrinted
error:&error];

//print out the data contents
Label1.text = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];

}
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
[self.mapView setShowsUserLocation:YES];
}
}

0

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …