flutter 腾讯云 上传腾讯云cos 使用flutter1.12 1.17及以上版本 ios与flutter混合开发

Posted YunusQ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flutter 腾讯云 上传腾讯云cos 使用flutter1.12 1.17及以上版本 ios与flutter混合开发相关的知识,希望对你有一定的参考价值。

flutter 腾讯云 上传腾讯云cos 使用flutter1.12 1.17及以上版本 ios与flutter混合开发

前言

腾讯云对Flutter极不友好 在其官方文档里没有给出flutter的官方插件 flutter插件网https://pub.dev/里唯一的插件经我反复尝试已经不能使用。现研究混合开发,又发现新的flutter版本(>1.12)已经不兼容旧的了,所以需要新的api接口。

这里是安卓的相关代码

https://blog.csdn.net/youtiankeng/article/details/107825986

首先注册腾讯云的cos相关功能

先腾讯云注册cos 获取各类参数名 bucket之类的值 之后会用

代码部分

在这里创建两个文件 下面是对应的代码

TencentCosPlugin.h

//
//  TencentCosPlugin.h
//  Runner
//
//  Created by 孔启超 on 2020/9/4.
//

//#ifndef TencentCosPlugin_h
//#define TencentCosPlugin_h
//
//
//#endif /* TencentCosPlugin_h */

#import <Foundation/Foundation.h>
#import <Flutter/Flutter.h>
#import "TencentCosPlugin.h"
NS_ASSUME_NONNULL_BEGIN
@interface TencentCosPlugin : NSObject<FlutterPlugin>
+ (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry;
@end
NS_ASSUME_NONNULL_END

TencentCosPlugin.m

//
//  TencentCosPlugin.m
//  Runner
//
//  Created by 孔启超 on 2020/9/4.
//

#import <Foundation/Foundation.h>
#import "TencentCosPlugin.h"
#import "QCloudCore.h"
#import "QCloudCOSXML/QCloudCOSXML.h"

@interface TencentCosPlugin()<QCloudSignatureProvider>
//NSDictionary *arguments;

@property (nonatomic, strong)NSDictionary *arguments;
@property (nonatomic, strong)FlutterMethodChannel *channel;
- (id)initWithChannel:(FlutterMethodChannel *)channel;
@end


@implementation TencentCosPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar 
    FlutterMethodChannel* channel = [FlutterMethodChannel
                                     methodChannelWithName:@"tencent_cos"
                                     binaryMessenger:[registrar messenger]];
    TencentCosPlugin* instance = [[TencentCosPlugin alloc] initWithChannel:channel];
    [registrar addMethodCallDelegate:instance channel:channel];


+(void)registerWithRegistry:(NSObject<FlutterPluginRegistry> *)registry
    //注册插件
    [TencentCosPlugin registerWithRegistrar:[registry registrarForPlugin:@"TencentCosPlugin"]];



- (id)initWithChannel:(FlutterMethodChannel *)channel;

    if (self = [super init]) 

        self.channel = channel;

    
    return self;


- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result 
    if ([@"getPlatformVersion" isEqualToString:call.method]) 
        result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
    else if ([@"TencentCos.uploadFile" isEqualToString:call.method]) 
        
        self.arguments = [call arguments];
        NSString *urlstr = self.arguments[@"localPath"];
        //获取后缀名
        NSString *str = urlstr;
        //在urlstr中查找. 获取文件后缀名
        NSRange range = [str rangeOfString:@"."];
        //用途是我们可以把他后面的值截取出来
        NSInteger fromIndex = range.length+range.location-1;
        //backScheme就是文件后缀名
        NSString *backScheme = [urlstr substringFromIndex:fromIndex];
        
        NSURL *url = [NSURL fileURLWithPath:urlstr];
//        NSString *region = self.arguments[@"region"];
        
        NSString *way = self.arguments[@"way"];
//        NSString *bucket = self.arguments[@"bucket"];
       
        QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];
//        configuration.appID = appid;

        configuration.signatureProvider = self;
        QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];
        // 服务地域简称
        endpoint.regionName = @"ap-shanghai";//服务地域名称,可用的地域请参考注释
        // 使用 HTTPS
        endpoint.useHTTPS = true;
        configuration.endpoint = endpoint;

        [QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];
        [QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:configuration];

        //上传文件
        QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];
        
        // Create universally unique identifier (object)

        CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);

        // Get the string representation of CFUUID object.

        NSString *uuidStr = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuidObject));
        //获取不带-的uuid
        NSString *uuidStrForaml = [uuidStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
        NSLog(@"%@", uuidStrForaml);
        
        CFRelease(uuidObject);
        NSString *strCospath;
        if ([way isEqualToString:@"video"]) 
          strCospath = [NSString stringWithFormat:@"%@%@%@%@%@", @"app/", way,@"/20.", uuidStrForaml,@".mp4"];
        
        else strCospath = [NSString stringWithFormat:@"%@%@%@%@%@", @"app/", way,@"/20.", uuidStrForaml,backScheme];
        NSLog(@"%@", strCospath);
        //拼接完整的url
        NSString *backurl = [NSString stringWithFormat:@"%@%@", @"https://kt-1301681474.cos.ap-shanghai.myqcloud.com/", strCospath];
        put.object = strCospath;
        put.bucket = @"kt-zzzz";/*自己的bucket*/
        put.body =  url;/*文件的URL*/;
    
        [put setSendProcessBlock:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) 

            NSLog(@"upload %lld totalSend %lld aim %lld", bytesSent, totalBytesSent, totalBytesExpectedToSend);
            NSMutableDictionary *data = [NSMutableDictionary dictionary];
            [data setValue:urlstr forKey:@"localPath" ];
            [data setValue:way forKey:@"way"];
            NSNumber *a = @(totalBytesSent);
            NSNumber *b = @(totalBytesExpectedToSend);
            NSNumber *c =@(a.doubleValue/b.doubleValue*100);
            [data setValue:c forKey:@"progress"];
            [self.channel invokeMethod:@"onProgress" arguments:data];
        ];
        [put setFinishBlock:^(id outputObject, NSError* error) 
            NSMutableDictionary *data = [NSMutableDictionary dictionary];
            [data setValue:urlstr forKey:@"localPath" ];
            [data setValue:way forKey:@"way"];
            if(error.code == 0)
                [self.channel invokeMethod:@"onSuccess" arguments:data];
               NSLog(@"成功上传图片");
//                result(@"0");
                result(backurl);
            else
                [data setValue: error.domain forKey:@"message"];
                [self.channel invokeMethod:@"onFailed" arguments:data];
                 result(@"1");
            

        ];
        [[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
    else 
       NSLog(@"找不到上传方法");
        result(FlutterMethodNotImplemented);
    

- (void) signatureWithFields:(QCloudSignatureFields*)fileds
                     request:(QCloudBizHTTPRequest*)request
                  urlRequest:(NSMutableURLRequest*)urlRequst
                   compelete:(QCloudHTTPAuthentationContinueBlock)continueBlock


    QCloudCredential* credential = [QCloudCredential new];
    credential.secretID = @"xxx"; // 永久密钥 SecretId
    credential.secretKey = @"yyy"; // 永久密钥 SecretKey

    // 使用永久密钥计算签名
    QCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc]
        initWithCredential:credential];
    QCloudSignature* signature = [creator signatureForData:urlRequst];
    continueBlock(signature, nil);

//- (void) signatureWithFields:(QCloudSignatureFields*)fileds
//                     request:(QCloudBizHTTPRequest*)request
//                  urlRequest:(NSMutableURLRequest*)urlRequst
//                   compelete:(QCloudHTTPAuthentationContinueBlock)continueBlock
//    /*向签名服务器请求临时的 Secret ID,Secret Key,Token*/
//    QCloudCredential* credential =  [QCloudCredential new];
//    credential.secretID = self.arguments[@"secretId"];
//    credential.secretKey = self.arguments[@"secretKey"];
//    credential.token = self.arguments[@"sessionToken"];
//    //    credential.expiretionDate     = self.arguments[@"sessionToken"];/*签名过期时间*/
//    QCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc] initWithCredential:credential];
//    QCloudSignature* signature =  [creator signatureForData:urlRequst];
//    continueBlock(signature, nil);
//
@end

然后再继续注册这个混合的插件

import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate 
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool 
    GeneratedPluginRegistrant.register(with: self)
    TencentCosPlugin.register(with:self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  

参考的官方文档

腾讯官方文档 https://cloud.tencent.com/document/product/436/12159
暂时使用的是永久秘钥
后续会考虑改用临时秘钥(官方也推荐使用临时秘钥,永远密码只作为开发环境使用)。

以上是关于flutter 腾讯云 上传腾讯云cos 使用flutter1.12 1.17及以上版本 ios与flutter混合开发的主要内容,如果未能解决你的问题,请参考以下文章

基于element-ui封装上传图片到腾讯云Cos组件

如何在typecho中使用腾讯云对象存储cos?

上传大文件到腾讯云cos遇到的一些问题

备份数据上传腾讯云COS

小程序开发:上传图片到腾讯云

微信小程序上传图片到COS腾讯云