我是新来的块,并且正在尝试弄清楚如何在执行我的操作之前等待块完成(在这种情况下为nslog),那么如何等待块完成在下面的代码执行此之前的NSLog:NSLog(@"convertedPhotos::%@",convertedImages);
在执行某些事情之前等待完成块
convertedImages = [[NSMutableArray alloc] init];
for (NSDictionary *photo in photos) {
// photo is a dictionary containing a "caption" and a "urlRep"
[photoUrls addObject:photo[@"urlRep"]];
}
if (photoUrls.count) {
for (id photos in photoUrls){
NSString *urlString = photos;
[self base64ImageAtUrlString:urlString result:^(NSString *base64) {
[jsonWithPhotos setObject:convertedImages forKey:@"photo64"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonWithPhotos
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"json::%@",jsonString);
}
}];
}
}
else {
NSLog(@"where are my urls?");
}
NSLog(@"convertedPhotos::%@",convertedImages);
}
}
这种方法/块从上方
- (void)base64ImageAtUrlString:(NSString *)urlString result:(void (^)(NSString *))completion {
NSURL *url = [NSURL URLWithString:urlString];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:url resultBlock:^(ALAsset *asset) {
// borrowing your code, here... didn't check it....
ALAssetRepresentation *representation = [asset defaultRepresentation];
CGImageRef imageRef = [representation fullResolutionImage];
//TODO: Deal with JPG or PNG
NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:imageRef], 0.1);
NSString *base64 = [imageData base64EncodedString];
completion(base64);
[convertedImages addObject:base64];
// NSLog(@"converted::%@",convertedImages);
} failureBlock:^(NSError *error) {
NSLog(@"that didn't work %@", error);
}];
}
您要拨打'的NSLog(@ “convertedPhotos ::%@”,convertedImages);'当每一个图像已经被处理? – Jkmn
通常你会把代码放在块的末尾...... – Wain
@Jkmn是的,这是正确的。 – BluGeni