我想将 post 数据的代码从 NSURLConnection 更改为 url 到 NSURLSession

I want to change my code of post data to url from NSURLConnection to NSURLSession

似乎每次我想编辑和更新我的应用程序时,Apple 都会更改一些阻止我的东西 'let me just edit that quickly and upload my new version'。他们现在已经禁用了对 Watch 使用 NSURLConnection 的可能性。我之前在 Watch 上使用过它,但现在看来 Apple 希望我使用 NSURLSession,但我似乎无法弄清楚它是如何工作的。这是我的代码,有人可以看一下,让我知道如何调整它,以便它可以与 NSURLSession 一起使用。

- (void)someFunction:(NSString *)startTime {
    // Download the json file
    NSUserDefaults *prefs = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.domain.something"];
    NSURL *jsonFileUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://aurlwithparameter%@&another%@", [prefs stringForKey:@"user_id"], startTime]];
    _starttedTime = startTime;
    // Create the request
    NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];

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

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [self.delegate connectionTimedOutMakingTempBlock:true];
}

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

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Create an array to store the locations

    // Parse the JSON that came in
    NSUserDefaults *prefs = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.domain.something"];

    [prefs setObject:_starttedTime forKey:@"temp_start_time"];

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

}

您可以使用以下代码段。 completionHandler 块替换了您将使用 NSURLConnection 的委托方法(例如 -connectionDidFinishLoading: 等)。

// Create the request
NSURLRequest *urlRequest = ...;

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

     // Handle success / error response here.

}];
 NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                                completionHandler:
                                      ^(NSData *data, NSURLResponse *response, NSError *connectionError) {
                                          // ...
                                          NSLog(@"coming inside session side");
                                          }];

这是最好的link你可以参考这个

NSURLSESSION LINK