美文网首页
Moya 上传数据的两种方式

Moya 上传数据的两种方式

作者: 小王在努力 | 来源:发表于2020-11-10 19:20 被阅读0次

1、前言

Moya网络请求封装不懂可以点击Moya封装

2、Moya上传视频

方法一、

public var task: Task {
        var params : [String : String] = [:]
        switch self {
        case let .uploadVideo(data: data):
            let time = String().timeStamp
            let auto_key = "FoFHDov5mTn3OriLeE9u3loOnIL6tp7q" + time
            params = ["from":"6","uuid":BaseMacro.uuid()," time":time,"auth_key":auto_key.md5String]
            let formData: [Moya.MultipartFormData] = [Moya.MultipartFormData(provider: .data(data), name: "video", fileName: "video.mp4", mimeType: "video/mp4")]
            return .uploadCompositeMultipart(formData, urlParameters: params)
        default:
            break;
        }
    }

方法二、

public var task: Task {
        var params : [String : String] = [:]
        switch self {
        case let .uploadVideo(data: data):
            let time = String().timeStamp
            let auto_key = "FoFHDov5mTn3OriLeE9u3loOnIL6tp7q" + time
            var formData: [Moya.MultipartFormData] = [Moya.MultipartFormData(provider: .data(data), name: "video", fileName: "video.mp4", mimeType: "video/mp4")]

            let fromData = "6".data(using: String.Encoding.utf8) ?? Data()
            formData.append(Moya.MultipartFormData(provider: .data(fromData), name: "from"))
            let timeData = time.data(using: String.Encoding.utf8) ?? Data()
            formData.append(Moya.MultipartFormData(provider: .data(timeData), name: "time"))
            let uuidData = "6".data(using: String.Encoding.utf8) ?? Data()
            formData.append(Moya.MultipartFormData(provider: .data(uuidData), name: "uuid"))
            let auth_key = auto_key.md5String.data(using: String.Encoding.utf8) ?? Data()
            formData.append(Moya.MultipartFormData(provider: .data(auth_key), name: "auth_key"))
            
            return .uploadMultipart(formData)
        default:
            break;
        }
    }

注意
1、name:是服务端视频定义的、比如服务端定义是file = xxxx.mp4 ,那么这里name就改为file
2、这里面包含4个参数分别是:from time uuid auth_key
3、这里data 是图片或者视频的格式,我们只需要将图片或者视频转为Data数据格式就可以了

3、接口的调用

       let path = Bundle.main.path(forResource: "video1", ofType: "mp4")
        print(path as Any)
        do{
            let data = try Data(contentsOf: URL(fileURLWithPath: path!), options: Data.ReadingOptions.alwaysMapped)
            ApiMoya.request(target: .uploadImage(data: data)) { (json) in
                
            } failure: { (error) in
                
            }

        }catch{
            
        }

相关文章

网友评论

      本文标题:Moya 上传数据的两种方式

      本文链接:https://www.haomeiwen.com/subject/bbnjbktx.html