1

我正在尝试UITableView通过获取 URL 来填充。为了避免冻结 UI,我使用dispatch_async(dispatch_queue_t queue, ^(void)block)异步获取。NSRunLoop在用于等待响应的异步块中。

这是我的获取代码:

- (BOOL)isFinished {
    return _finished;
}

- (void)startReceive {
    NSURLRequest* request = [NSURLRequest requestWithURL:self.baseURL];
    self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
    assert(self.connection);
}

- (void)stopReceiveWithStatus:(NSString*)statusCode {
    if (self.connection) {
        [self.connection cancel];
        self.connection = nil;
    }
    self.finished = YES;
    NSLog(@"Stop Receive with status code %@", statusCode);
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    assert(connection == self.connection);
    NSHTTPURLResponse* httpResponse = nil;
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        httpResponse = (NSHTTPURLResponse*) response;

        if (httpResponse.statusCode != 409) {
            // I need 409 to fetch some data
            [self stopReceiveWithStatus:[NSString stringWithFormat:@"HTTP error %2d", httpResponse.statusCode]];
        }
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    assert(connection == self.connection);
    self.sessionID = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    assert(connection == self.connection);

    [self stopReceiveWithStatus:@"Connection failed"];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    assert(connection == self.connection);

    [self stopReceiveWithStatus:nil];
}

UITableViewController:

// refreshControl handler
- (IBAction)refresh {
    [self startRefreshingAnimation];
    dispatch_queue_t loaderQ = dispatch_queue_create("loading transmission data", NULL);
    dispatch_async(loaderQ, ^{
        [self foo]; 
        while(!self.t.finished) {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self endRefreshingAnimation]; // end
        });
    });
}

- (void)foo {
    NSLog(@"session id: %@", self.t.sessionID);
}

sessionID将在 HTTP 请求完成后填充。现在的问题是我无法得到第sessionID一次调用的时间,因为第一次它没有被填充,第二次它工作得很好。第一次打电话时如何获取?

我是 iOS 新手。如果您有更好的解决方案来解决这个问题,请告诉我,谢谢。

4

2 回答 2

0

有一个很好的框架,不要浪费你的时间。

https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking

更新。您可以执行以下请求:

NSURL *url = self.baseURL;
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                    height, @"user[height]",
                    weight, @"user[weight]",
                    nil];
[httpClient postPath:@"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"Request Successful, response '%@'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
}];
于 2013-08-27T09:46:53.700 回答
0

您应该使用第三方库来处理网络连接,例如STHTTPRequest

STHTTPRequest *r = [STHTTPRequest requestWithURLString:@"http://www.apple.com"];

r.completionBlock = ^(NSDictionary *headers, NSString *body) {
    // ...
};

r.errorBlock = ^(NSError *error) {
    // ...
};

[r startAsynchronous];
于 2013-08-27T10:50:19.867 回答