我是这个领域的初学者,在ios上使用数据库。不过,我可以找到连接到mysql数据库的方法,下载并解析json提要。现在在ios 9中,我不能再使用nsurlconnection了,所以我必须用nsurlsession替换它。我在这里看到了许多教程,例如this。到目前为止,我还不能更换它。因为我有时间压力,我不能浪费更多的时间来做这件事。有人能帮我换吗?
我的代码如下:

- (void)downloadItems
{
    // Download the json file
    NSURL *jsonFileUrl = [NSURL URLWithString:@"http://myhost.ch/test.php"];

    // Create the request
    NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];

    // Create the NSURLConnection
    [NSURLConnection connectionWithRequest:urlRequest delegate:self];

}

#pragma mark NSURLConnectionDataProtocol Methods

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

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the newly downloaded data
    [_downloadedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Create an array to store the locations
    NSMutableArray *_locations = [[NSMutableArray alloc] init];

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

    // 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];

        // Create a new location object and set its props to JsonElement properties
        Location *newLocation = [[Location alloc] init];
        newLocation.idS = jsonElement[@"idStatistic"];
        newLocation.temp = jsonElement[@"temp"];
        newLocation.hum = jsonElement[@"hum"];
        newLocation.date_time = jsonElement[@"date_time"];

        // Add this question to the locations array
        [_locations addObject:newLocation];
    }

    // Ready to notify delegate that data is ready and pass back items
    if (self.delegate)
    {
        [self.delegate itemsDownloaded:_locations];
    }
}

最佳答案

你可以试试这个,
{
nsurl*url=[nsurl urlWithString:@“http://myhost.ch/test.php”];

NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];

[theRequest setHTTPMethod:@"POST"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:theRequest
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  responseDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
                                  NSLog(@"Result:%@", responseDict);
                              }];
[task resume];

}

10-08 08:12