我是新來的塊,並且正在嘗試弄清楚如何在執行我的操作之前等待塊完成(在這種情況下爲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