1

似乎每次我想编辑和更新我的应用程序时,Apple 都会改变一些阻止我“让我快速编辑并上传我的新版本”的东西。他们现在禁用了使用 NSURLConnection 作为 Watch 的可能性。我以前在 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];
    }
}

}

4

2 回答 2

1

您可以使用以下代码段。该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.

}];
于 2016-02-19T13:04:02.173 回答
1
 NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                                completionHandler:
                                      ^(NSData *data, NSURLResponse *response, NSError *connectionError) {
                                          // ...
                                          NSLog(@"coming inside session side");
                                          }];

这是您可以参考的最佳链接

NSURLSESSION 链接

于 2016-02-19T13:36:50.637 回答