从其他问题看来,我所要做的就是在我的变量前面添加 __block,但是,它似乎对我不起作用。
在块内,使用 NSLog() 检查时,令牌被正确分配。如果我在返回令牌之前再次检查它;它变为 NULL。
- (NSString *)extractTokenFromURL:(NSURL *)tokenURL
{
__block NSString *token = nil;
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
delegate:self
delegateQueue:nil];
[[session dataTaskWithURL:self.tokenURL
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
if (httpResp.statusCode == 200) {
NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSRange divRange = [content rangeOfString:@"<div id='token' style='display:none;'>" options:NSCaseInsensitiveSearch];
if (divRange.location != NSNotFound) {
NSRange endDivRange;
endDivRange.location = divRange.length + divRange.location;
endDivRange.length = [content length] - endDivRange.location;
endDivRange = [content rangeOfString:@"</div>" options:NSCaseInsensitiveSearch range:endDivRange];
if (endDivRange.location != NSNotFound) {
divRange.location += divRange.length;
divRange.length = endDivRange.location - divRange.location;
dispatch_async(dispatch_get_main_queue(), ^{
token = [content substringWithRange:divRange];
});
}
}
}
}
}] resume];
return token;
}