iOS上传文件到谷歌云存储 – 得到401:“需要login”
我无法确定如何将file upload到公共访问存储桶到云存储。
- 我已经build立了一个存储桶,并将其ACL设置为对所有用户进行读取和写入。
- 我启用了云存储JSON API和云存储API。
- 我为浏览器应用程序创build了一个允许任何引用者的API密钥。
这是我在Swift中的代码:
private lazy var googleServiceStorage:GTLServiceStorage = { var storage = GTLServiceStorage() storage.APIKey = "AIzaSy**********m8TPCM" storage.additionalHTTPHeaders = ["x-goog-project-id" : "159*******7"] return storage }() } public func uploadAssetToGoogle(resourcePath: String?) { if let _resourcePath = resourcePath { let fileHandle = NSFileHandle(forReadingAtPath: _resourcePath) let uploadParams = GTLUploadParameters(fileHandle: fileHandle, MIMEType: "video/mov") var storageObject = GTLStorageObject.object() as GTLStorageObject storageObject.name = "12345678" let query = GTLQueryStorage.queryForObjectsInsertWithObject(storageObject, bucket: "my-bucket", uploadParameters: uploadParams) as GTLQuery var ticket = googleServiceStorage.executeQuery(query) { ticket, object, error in if let _error = error { println("Error upload file: \(error.localizedDescription) : \(error.localizedFailureReason)") return } println("Upload succeeded") } ticket.uploadProgressBlock = {ticket, numberOfBytesRead, dataLength in println("Ticket: \(ticket)") NSLog("read %llu from %llu bytes", numberOfBytesRead, dataLength) } }
当我调用这个代码时,我在控制台中得到以下输出:
mediaURL type: (Metatype) - file:///Users/Michael/Library/Developer/CoreSimulator/Devices/5895B7FA-41E7-4958-84FD-2C1043CA7CD7/data/Containers/Data/Application/2DD62539-E364-4BE0-A89C-E0DD2827D74B/tmp/trim.FCE68DAD-0FC6-4E2D-8C92-37055A02DD12.MOV Ticket: GTLServiceTicket 0x7feed4860660: {service:<GTLServiceStorage: 0x7feed2cf9d90> devKey:AIzaSyBClcLHWtXzlBHb2VbATA1xIlUO0m8TPCM fetcher:GTMHTTPUploadFetcher 0x7feed4890fb0 (https://www.googleapis.com/upload/rpc?uploadType=resumable&prettyPrint=false) } 2014-09-25 18:25:23.515 Beta[14917:1971326] read 202 from 29512 bytes Error upload file: The operation couldn't be completed. (Login Required) : Optional("(Login Required)")
有一些我想念,但我不明白。 如果有人能帮助我的话,它会为我节省更多的头发。
对于需要login的错误消息,尝试添加新的存储桶权限项目
ENTITY = User, NAME = allUsers, ACCESS = Writer
请注意:您必须使用
Server API key
而不是iOS API key
对于对象上传,可以添加GTLStorageObjectAccessControl
GTLStorageObjectAccessControl *objAccessControl = [GTLStorageObjectAccessControl new]; objAccessControl.entity = @"allUsers"; objAccessControl.email = @"xxxxxx-xxxxx@developer.gserviceaccount.com"; objAccessControl.role = @"OWNER"; GTLStorageObject *newObject = [GTLStorageObject object]; newObject.name = @"image.png"; newObject.acl = @[objAccessControl];
比,
GTLQueryStorage *query = [GTLQueryStorage queryForObjectsInsertWithObject:newObject bucket:kBucketName uploadParameters:uploadParameters];