You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS中用TUC Library存图片到相册并获取路径(Objective-C)

Solution to Get Saved Image Path with TUC Library

Hey there! I see you're using the TUC Library to save images to a custom Photos album, and you need the local path of the saved image for your chat interface. Let's break down how to make this work.

Your current code only notifies you if the save succeeded or failed, but doesn't give you access to the saved image's details. Here's how to extend it to get the path:

Step 1: Extend the TUC Library's Save Method (If Needed)

First, check if the existing TUCAssetsHelper category has a method that returns the saved PHAsset (the Photos framework object representing the image). If not, you can extend the UIImage category to add a success callback that includes the asset:

// Add this to your UIImage+TUCAssetsHelper.h file
typedef void(^TUCSaveImageSuccessWithAssetBlock)(PHAsset *savedAsset);

- (void)tuc_saveToAlbumWithAlbumName:(NSString *)albumName 
                   successWithAsset:(TUCSaveImageSuccessWithAssetBlock)success 
                           failure:(TUCAssetsHelperFailureBlock)failure;

// Implement in UIImage+TUCAssetsHelper.m
- (void)tuc_saveToAlbumWithAlbumName:(NSString *)albumName 
                   successWithAsset:(TUCSaveImageSuccessWithAssetBlock)success 
                           failure:(TUCAssetsHelperFailureBlock)failure {
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        // Replicate the existing save logic from the TUC Library here
        // This includes creating the album if it doesn't exist and adding the image
    } completionHandler:^(BOOL saveSuccess, NSError *error) {
        if (saveSuccess && success) {
            // Fetch the most recently saved image asset
            PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
            fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
            fetchOptions.fetchLimit = 1;
            
            PHFetchResult *recentAssets = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
            PHAsset *savedAsset = recentAssets.firstObject;
            
            // Call the success callback on the main thread
            dispatch_async(dispatch_get_main_queue(), ^{
                success(savedAsset);
            });
        } else {
            if (failure) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    // Map the error to the appropriate authorization status
                    TUCAssetsHelperAuthorizationStatus status = TUCAssetsHelperAuthorizationStatusDenied;
                    if (error.code == PHErrorAuthorizationDenied) {
                        status = TUCAssetsHelperAuthorizationStatusDenied;
                    } else {
                        status = TUCAssetsHelperAuthorizationStatusFailed;
                    }
                    failure(status);
                });
            }
        }
    }];
}

Step 2: Use the Extended Method to Get the Local Path

Once you have access to the saved PHAsset, you can use the Photos framework to retrieve its local file URL:

[image tuc_saveToAlbumWithAlbumName:@"SUPImages" 
                   successWithAsset:^(PHAsset *savedAsset) {
    NSLog(@"Save to custom album succeeded!");
    
    PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
    requestOptions.synchronous = YES; // Set to NO if you want async loading
    requestOptions.networkAccessAllowed = YES; // Allow downloading from iCloud if needed
    requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    
    [[PHImageManager defaultManager] requestImageDataAndOrientationForAsset:savedAsset
                                                                    options:requestOptions
                                                              resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
        // Extract the local file URL from the info dictionary
        NSURL *localImageURL = info[PHImageFileURLKey];
        if (localImageURL) {
            NSString *imagePath = localImageURL.path;
            NSLog(@"Saved image local path: %@", imagePath);
            
            // Use this imagePath in your chat interface now!
            // Remember to dispatch UI updates to the main thread if needed
            dispatch_async(dispatch_get_main_queue(), ^{
                // Update your chat UI with the image path
            });
        }
    }];
} failure:^(TUCAssetsHelperAuthorizationStatus status) {
    NSLog(@"Save to custom album failed: %@", status == TUCAssetsHelperAuthorizationStatusDenied ? "Permission denied" : "Unknown error");
}];

Key Notes

  • Permissions: Make sure you've requested photo library access in your Info.plist (add NSPhotoLibraryAddUsageDescription and NSPhotoLibraryUsageDescription keys with appropriate messages).
  • iCloud Images: If the image is stored in iCloud, networkAccessAllowed = YES will trigger a download if needed. Handle loading states in your chat UI for this case.
  • Main Thread: Always update UI elements on the main thread, so wrap any chat interface updates in dispatch_async(dispatch_get_main_queue(), ^{ ... }).

内容的提问来源于stack exchange,提问作者Bilal Hassan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:41:33