unity ios 下载图片并将图片保存至相册

  1. unity 中 c#的编写
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
using System.IO;

public class save : MonoBehaviour {

//这个方法就是引用在 xcode 中编写的方法,与 iOS 连接的桥梁
    [DllImport("__Internal")]
    private static extern void _SavePhoto(string readAddr);

    public void Click()
    {
        StartCoroutine(SavePic());
    }
    
    IEnumerator SavePic()
    {
        
        WWW www = new WWW(请求下载接口);
        yield return www;
        byte[] file = www.bytes;
        int length = file.Length;
        Stream sw;
        FileInfo File = new FileInfo(Application.persistentDataPath+"/证书.png");
        sw = File.Create();
        sw.Write(file, 0, length);
        sw.Close();
        sw.Dispose();
        _SavePhoto(Application.persistentDataPath + "/证书.png");
    }
}
  • 先去请求下载文件,文件下载下来后存放在<Application.persistentDataPath+"/证书.png">在这个路径下,然后在调用xcode 编写的方法(_SavePhoto)并提供图片所在路径保存至相册
  1. Xcode 中的操作
  • 新建文件PhotoManager.h
#import <Foundation/Foundation.h>

@interface PhotoManager : NSObject
- ( void ) imageSaved: ( UIImage *) image didFinishSavingWithError:( NSError *)error
    contextInfo: ( void *) contextInfo;
@end
  • 新建文件PhotoManager.m
#import "PhotoManager.h"

@implementation PhotoManager
- ( void ) imageSaved: ( UIImage *) image didFinishSavingWithError:( NSError *)error
          contextInfo: ( void *) contextInfo
{
    if (error != nil)
    {
        NSLog(@"有错误");
    }
    else
    {
        NSLog(@"保存结束");
    }
}


void _SavePhoto(char *readAddr)
{
    NSString *strReadAddr = [NSString stringWithUTF8String:readAddr];
    UIImage *img = [UIImage imageWithContentsOfFile:strReadAddr];
    NSLog(@"%@",[NSString stringWithFormat:@"w:%f, h:%f", img.size.width, img.size.height]);
    NSLog(@"%@",[NSString stringWithFormat:@"%s",readAddr ]);
    PhotoManager *instance = [[PhotoManager alloc]init];
    UIImageWriteToSavedPhotosAlbum(img, instance,
                                   @selector(imageSaved:didFinishSavingWithError:contextInfo:), nil);
}


@end

-将上面两个文件放在 xcode工程下的unity 文件夹下

  • 设置权限,给应用设置可以访问相册的权限
    • Privacy-Photo Library Additions Usage Description(相册添加权限)

版权声明:本文为star__119原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。