Coder Social home page Coder Social logo

tuskit's Introduction

TUSKit

An iOS client written in Swift for TUS resumable upload protocol.

Protocol Version SwiftPM compatible License Platform

With this client, you can upload regular raw Data or file-paths.

Usage

You can refer to the example project to see how TUSKit is implemented.

As a starting point, please refer to the SceneDelegate.

Here is how you can instantiate a TUSClient instance.

Be sure to store a reference to the client somewhere. Then initialize as you normally would.

final class MyClass {
  let tusClient: TUSClient
  
  init() {
      tusClient = TUSClient(server: URL(string: "https://tusd.tusdemo.net/files")!, sessionIdentifier: "TUS DEMO", storageDirectory: URL(string: "TUS")!)
      tusClient.delegate = self
  }
}

Note that you can register as a delegate to retrieve the URL's of the uploads, and also any errors that may arise.

Note that you can pass your own URLSession instance to the initializer.

You can conform to the TUSClientDelegate to receive updates from the TUSClient.

extension MyClass: TUSClientDelegate {
    func didStartUpload(id: UUID, client: TUSClient) {
        print("TUSClient started upload, id is \(id)")
        print("TUSClient remaining is \(client.remainingUploads)")
    }
    
    func didFinishUpload(id: UUID, url: URL, client: TUSClient) {
        print("TUSClient finished upload, id is \(id) url is \(url)")
        print("TUSClient remaining is \(client.remainingUploads)")
        if client.remainingUploads == 0 {
            print("Finished uploading")
        }
    }
    
    func uploadFailed(id: UUID, error: Error, client: TUSClient) {
        print("TUSClient upload failed for \(id) error \(error)")
    }
    
    func fileError(error: TUSClientError, client: TUSClient) {
        print("TUSClient File error \(error)")
    }
    
    
    func totalProgress(bytesUploaded: Int, totalBytes: Int, client: TUSClient) {
    }
    
    
    func progressFor(id: UUID, bytesUploaded: Int, totalBytes: Int, client: TUSClient) {

    }
    
}

Starting an upload

A TUSClient can upload Data or paths to a file in the form of a URL.

To upload data, use the upload(data:) method`

let data = Data("I am some data".utf8)
let uploadId = try tusClient.upload(data: data)

To upload multiple data files at once, use the uploadMultiple(dataFiles:) method.

To upload a single stored file, retrieve a file path and pass it to the client.

let pathToFile:URL = ...
let uploadId = try tusClient.uploadFileAt(filePath: pathToFile)

To upload multiple files at once, you can use the uploadFiles(filePaths:) method.

Custom upload URL and custom headers

To specify a custom upload URL (e.g. for TransloadIt) or custom headers to be added to a file upload, please refer to the uploadURL and customHeaders properties in the methods related to uploading. Such as: upload, uploadFileAt, uploadFiles or uploadMultiple(dataFiles:).

Measuring upload progress

To know how many files have yet to be uploaded, please refer to the remainingUploads property.

Please note that there isn't a percentage supplied, since it's up to you to define what the starting point is of an upload. For example. If you upload 10 files, and 3 are finished, then you are at 3/10. However, if during this upload you add 2 more, should that count as 3/12 or do you consider it a a fresh upload? So 0/9. It's up to you to define how finished uploads are counted when adding new uploads.

For byte level progress. Please implement the TUSClientDelegate protocol and set it as a the delegate property of TUSClient.

Upload id's and contexts

By starting an upload you will receive an id. These id's are also passed to you via if you implement the TUSClientDelegate. You can use these id's to identify which files are finished or failed (but you can also use contexts for that, see below). You can also delete these files on failure if you want. You can also use these id's to retry a failed upload.

Note that TUSClient will automatically retry an upload a few times, but will eventually give up, after which it will report an error. After which you can call the retry method and try again.

Contexts

You can use id's to monitor progress and perform other tasks, such as stopping uploads. But you can also pass a context with richer information. TUSKit will return this context through various delegate calls. This way you don't have to keep track of the status of upload id's. You can pass in a small object with information, and you receive this from TUSKit.

Security notice: TUSKit will store this context on the disk next to other file metadata. This is to maintain the information between sessions.

Starting a new session

An upload can fail at any time. Even when an app is in the background.

Therefore, after starting a new app session, we recommend you inspect any failed uploads that may have occurred and act accordingly. For instance, you can decide to do something with the failed uploads such as retrying them, deleting them, or reporting to the user.

For instance, here is how you can initialize the client and check its failed uploads. Note that we first fetch the id's, after which retry the uploads.
  
tusClient = TUSClient(server: URL(string: "https://tusd.tusdemo.net/files")!, sessionIdentifier: "TUS DEMO", storageDirectory: URL(string: "/TUS")!)
tusClient.delegate = self
tusClient.start()
        
do {
  // When starting, you can retrieve the locally stored uploads that are marked as failure, and handle those.
  // E.g. Maybe some uploads failed from a last session, or failed from a background upload.
  let ids = try tusClient.failedUploadIds()
  for id in ids {
    // You can either retry a failed upload...
    try tusClient.retry(id: id)
    // ...alternatively, you can delete them too
    // tusClient.removeCacheFor(id: id)
  }
} catch {
  // Could not fetch failed id's from disk
}

Background uploading

When you incorporate background uploading, we strongly recommend you to inspect any failed uploads that may have occured in the background. Please refer to Starting a new Session for more information.

iOS can leverage a background URLSession to enable background uploads that continue when a user leaves your app or locks their device. For more information, take a look at Apple's docs on background URLSession. The docs focus on downloads but uploads follow pretty much the exact same principles.

To make incorporating background uploads as straightforward as possible, TUSKit handles all the complex details of managing the URLSession and delegate callbacks. As a consumer of TUSKit all you need to do is leverage the new initializer on TUSClient as shown below:

do {
    tusClient = try TUSClient(
        server: URL(string: "https://tusd.tusdemo.net/files")!,
        sessionIdentifier: "TUS DEMO",
        sessionConfiguration: .background(withIdentifier: "com.TUSKit.sample"),
        storageDirectory: URL(string: "/TUS")!,
        chunkSize: 0
    )
} catch {
    // ...
}

The easiest way to set everything up is to pass a URLSession.background configuration to the TUSClient. If you require a different configuration or don't want any background support at all, you're free to pass a different configuration.

Because TUSKit can now have uploads running while your app is no longer actively in memory, you should always use the getStoredUpload method on TUSClient on app launch to retrieve all stored uploads and extract information about which uploads are currently completed. Afterwards you can call cleanup to allow TUSClient to remove metadata for completed items. See the sample app for more details.

Limitations and constraints for background uploads on iOS

The primary source for information on how background uploads work will always be Apple's own documentation on performing network calls in the background. TUSKit is limited and bound by what's possible and allowed by the system.

In practice, this means that you should always schedule all of your uploads while the app is in the foreground. Scheduling more uploads while an app is in the background is not allowed and will result in the system deprioritizing your requests.

For this reason, chunking is strongly discouraged when you intend to leverage background uploads since you would have to make several network calls, one after the other, to complete your upload.

It's also important to understand that iOS will automatically wait for your user to have a network connection before attempting to start your upload. This means your uploads might take a while to start. If a network connection drops while an upload is in progress, iOS will attempt to re-upload your file automatically.

By default, iOS will retry the full upload instead of resuming where the upload has left off. Unfortunately we haven't found a way to prevent iOS from doing this. On iOS 17 Apple has adde support for resumable uploads. We're currently exploring how we can integrate TUSKit with this feature since both iOS and TUSKit rely on the same protocols.

Warning: information below is deprecated in TUSKit 3.2.0.

Available from iOS13, you can schedule uploads to be performed in the background using the scheduleBackgroundTasks() method on TUSClient.

Scheduled tasks are handled by iOS. Which means that each device will decide when it's best to upload in the background. Such as when it has a wifi connection and late at night.

As an example from the SceneDelegate found in the example app, you can schedule them accordingly:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    // ... snip
    
    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        tusClient.scheduleBackgroundTasks()
    }
}

TUS Protocol Extensions

The client assumes by default that the server implements the Creation TUS protocol extension. If your server does not support that, please ensure to provide an empty array for the supportedExtensions parameter in the client initializer.

Example app

Please refer to the example app inside this project to see how to add photos from a PHPicker, using SwiftUI. You can also use the PHPicker mechanic for UIKit.

Parallelism

At the time of writing, this client does not support TUS' concatenation option. It does, however, automatically support parallel uploads in a single client. It does also support multiple clients.

Underlying Mechanics

The TUSClient will retry a failed upload two times (three total attempts) before reporting it as an error.

The TUSClient will try to upload a file fully, and if it gets interrupted (e.g. broken connection or app is killed), it will continue where it left of.

The TUSClient stores files locally to upload them. It will use the storageDirectory path that is passed in the initializer. Or create a default directory inside the documentsdir at /TUS .

The TUSClient will automatically removed locally stored files once their upload is complete.

Multiple instances

TUSClient supports multiple instances for simultaneous unrelated uploads.

Warning: Multiple clients should not share the same storageDirectory. Give each client their own directory to work from, or bugs may occur.

Please note that TUSClient since version 3.0.0 is not a singleton anymore.

If you strongly feel you want a singleton, you can still make one using the static keyword.

final class MyClass {
  static let tusClient: TUSClient = ...
}

But we discourage you from doing so because it makes resetting between tests harder, and it becomes problematic in a multi-threaded environment.

tuskit's People

Contributors

acconut avatar andreaslindahl avatar bradpatras avatar clementleroy avatar dmtrpetrov avatar donnywals avatar elvirion avatar justin-distaulo avatar justin-workjam avatar kiyosoft avatar kvz avatar m3t8d1tr avatar martinlau7 avatar mmasterson avatar pathakmanvendu avatar rick51231 avatar ruslanskorb avatar spatialbits avatar srvarma7 avatar tjeerdintveen avatar tombaileywzd avatar tursunovic avatar zmetser avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tuskit's Issues

Downloading data.

I need to download same as Uploading. How can download it.
please help me.

Upload to Vimeo : <TUSResumableUpload.m:(336)> Server responded to create file with 405

Hello,

Someone try to upload to vimeo a video with TUSKit ?

I try to use it but when i upload, i get this error :

TUSResumableUpload.m:(336) Server responded to create file with 405

Below my code :
`NSURL * applicationSupportURL = [[[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask] firstObject];

TUSUploadStore * uploadStore = [[TUSFileUploadStore alloc] initWithURL:[applicationSupportURL URLByAppendingPathComponent:@"temp_vimeo_tus_upload"]];

self.tusSession = [[TUSSession alloc] initWithEndpoint:[[NSURL alloc] initWithString:upload_url] dataStore:uploadStore allowsCellularAccess:YES];

NSDictionary *dict_head = @{@"Tus-Resumable" : @"1.0.0",
         @"Upload-Offset":@"0",
         @"Content-Type" : @"application/offset+octet-stream",
                            @"Accept" :accept
};

TUSResumableUpload *upload = [self.tusSession createUploadFromFile:videoToUploadUrl headers:nil metadata:nil];


        upload.progressBlock = progressBlock;
        upload.resultBlock = resultBlock;
        upload.failureBlock = failureBlock;

        [upload resume];`

Maybe something that i don't understand

Swift rewrite discussion

Re writing the library in swift in the swift-development branch
original gist

Proposed changes for TUSKit

Goals

  • Ditch objective-c and adopt Swift
  • Change blocks to delegates
  • Replicate the flow of the Android TUS library to bring synergy to TUS mobile native development
  • Make it easier for multiple file uploads
  • Better support for background sessions

Proposed new usage

// Init and setup the file upload url
TUSConfig {
url: "UPLOAD URL HERE"
sessionConfig: SOME_URL_SESSION_CONFIG //Not required, if not set the default session config will be set
}

TUSClient.setup(config) //MUST BE FIRED FIRST, AppDelegate on launch suggested 

// To access the client, use the singlegton
var client = TUSClient.shared

//Set the delegate 
client.delegate = self

//You can also change the file upload URL at anytime
client.uploadURL = "https://newUploadURL.com/files"

//Create a TUS Upload per file you want to upload
//On creation of an upload, the data of an object will be saved to the device until completion of the upload
var newUpload = TUSUpload(withId: "Some Id to refrence a file", andFile: "FilePathHere")
var anotherNewUpload = TUSUpload(withId: "Another Id to refrence a file", andData: DataObject)
var previousUpload = TUSUpload(withId: "Just an ID of a past upload")

//Misc functions for TUSUpload
newUpload.cancel()
newUpload.retry()


//Misc functions for client
client.currentUploads() //an array of TUSUpload objects of uploads unfinished
client.uploadStatus //An enum TUSStatus - either set to `uploading` `paused` `finished`
client.retryAll()
client.resumeAll()
client.cancelAll()
client.cleanUp() //Deletes local files of canceled or failed uploads - Files cannot be resumed after this is fired

//Now upload
client.createOrResumeUpload(TUSUploadObjectHere)
//or
client.createOrResumeUpload(TUSUploadObjectHere, withRetries: 3)


//TUSKitDelegate

func TUSProgress(bytesUploaded, bytesRemaining) //overall current upload progress

func TUSProgress(TUSUpload, bytesUploaded, bytesRemaining) //Per file upload progress

func TUSSuccess(TUSUpload, TUSResponse)

func TUSFailure(TUSUpload, TUSResponse, Error)

Remaining tasks

  • Custom Session Configs to be passed to clients
    • Sub task: SSL Pinning
  • TUS Create Post Call
  • TUS Upload Via Chunking
  • TUS Get call for file
  • TUS Resuming
    • State persistence
    • Resuming from last offset/chunk
  • TUS Response handling
    • Success file creation
    • Success file upload
    • Failed file storage
    • Bad server response

with server

can work with leblanc-simon/php-tus,php-tus has a server solution, so tus-ios-client can work with it .....

App extension support

I'm getting 'sharedApplication' is unavailable: not available on iOS (App Extension) - Use view controller based solutions where appropriate instead.

Is it possible, or, what would the best solution be?

I share my networking layer across Share Extension and my main application but am unable to compile the application when.

Duplicate

Hi there,

I needed to use this client and had to make a few changes to get it to work. I also put it on Cocoapods. I changed the layout of the project to be more standard.

Anyway, I thought it worth offering to just transfer it to you guys if you'd like it. It's here: michaelavila/TUSKit, Let me know. As it stands the client you have in your repo does not work with any TUS servers. It has to do with a change in the headers, Final-Length should be Entity-Length. I've made that change already in my repo. And have verified that it works.

Let me know if you all want it. Take care.

Can't resume upload after restarting app

I can't find a way to resume the last upload after restarting app. Is there a way to resume uploading the same file to the same temporary file ? Thank you
(I found that the upload id is different from the last upload id and the file will be uploaded to a new temporary file.)

Here is my codes written by swift4

    let asset = PHAsset.fetchAssets(withLocalIdentifiers: [media.mediaId], options: PHFetchOptions()).firstObject!
    let resource = PHAssetResource.assetResources(for: asset).first!
    let resourceURL = resource.value(forKey: "fileURL") as! URL
    
    let serverUrl = URL(string: "http://192.168.1.111:1080/files/")
    let uploadStore = TUSFileUploadStore(url: resourceURL)
    let session = TUSSession(endpoint: serverUrl!, dataStore: uploadStore!, allowsCellularAccess: true)
    let upload = session.createUpload(fromFile: resourceURL, retry: 3, headers: nil, metadata: nil)
           
    upload?.setChunkSize(1024*10)
    upload?.progressBlock = {
        (bytesWritten, bytesTotal) in
        print("upload progress = \(bytesWritten)/\(bytesTotal)")
    }
    
    upload?.failureBlock = {
        error in
        completionHandler("fail")
    }
    
    upload?.resultBlock = {
        fileURL in
        completionHandler("\(fileURL)")
    }
    
    upload?.resume()

is there any method for setting retry count?

i'm using TUSKit for iOS client.

i heard android version of library supports retry count. but i can't find it in iOS version.

i can use failure block when bad url, not supported url, not found host, and http status code in 500 to 600.

otherwise TUSKit automatically retry infinitely.

is there any method to setting retry count? or is there any plan to support retry count?

thanks

Why use UserDefaults store data

I saw that the previous issue mentioned that FileManager is used to read sandbox files, and why userdefaults is used now.

Our app use scenario is to select up to 55 resources (pictures, videos, documents) at a time, of which the document size is limited to 100m and the video length is not limited. Is our app really suitable for using userdefaults to store the files to be uploaded?

In the demo of 2.0.7-alpha, I used the iPhone 11 Pro Max simulator

Operation steps:

  1. Click "add file" to select a photo;

  2. Click "upload files" and the progress bar hasn't changed. The debugging window hasn't printed any information. I don't know what's wrong

  3. Run the app again, click "tlphoto" to select a picture, click "OK", and the app will crash directly

Issue when upload to Vimeo : TUSKit say success but vimeo waiting upload

Hello,

It is an issue I have, I wanting to know if you get this issue too…

I have uploading a video with TUSKit.
TUSKit block result is trigger, but Vimeo is still waiting the upload.

I asked Vimeo to see if if the problem is on their side.
But if someone have this issue… an help will be good :)

Is that possible that success block was trigger but to say that video is not upload ?

Headers and Metadata in Swift

Which is the right position and name to insert "Upload-Length","Upload-Offset" and etc.? Where is their location, headers or metadata?
let upload: TUSResumableUpload = tusSession.createUpload(fromFile: fileURl, headers: ["Authorization":"Bearer " + token], metadata: ["":""])

Not able to Upload large file

Hello,

I have implemented TUSKit successfully in code with swift 4 and xcode 9 and videos are uploaded successfully as well.

Problem that i am facing is if i select large videos and start to upload it will started upload video but after uploading few bytes (80%) it will start to upload again from 0 bytes in progress block thus it will not uploaded fully video

Can you please suggest why this happens with large video ?

Thanks

Custom head and chunck size.

In order to upload my files I need to add some credentials to the header however I can't seem to find out how to do this. I'm looking for whatever the equivilent is to --header in the terminal. Similarly I'm looking to change the chunk size similar to --chunck-size. Is there any way to do this using TUSKit?

SSL support

Does this library support HTTPS links?
Basically, we are trying to implement SSL pinning at iOS end with a self signed certificate.

Carthage support

Do you plan to add support for Carthage users?

Even if not, it would be great to add instructions how to install the lib manually. Not everyone uses CocoaPods. Thanks.

Attempting to store >= 4194304 bytes of data in CFPreferences/NSUserDefaults on this platform is invalid

Hi,

I am using new swift lib for this awesome project but I am getting error when trying to store data in UserDefaults. So if we have video of 100MB do we really want to store that in user defaults? Is there any workaround for this issue?

Issue seems to be in TUSClient.swift on line 88 where it says:
try UserDefaults.standard.set(Data(contentsOf: path), forKey: tusName)

Thanks and keep up the good work

File is marked as completed when more has been uploaded than expected

Reading this code, it seems like if data has been uploaded before a callback is received and we attempt to resume the upload (e.g. the server offset is ahead of the local offset) then we mark the file as complete. I believe the second-to-last line should read size >= [[self data] length] or similar.

- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSDictionary *headers = [httpResponse allHeaderFields];

    switch([self state]) {
        case CheckingFile: {
            if ([httpResponse statusCode] != 200 || [httpResponse statusCode] != 201) {
                TUSLog(@"Server responded with %ld. Restarting upload",
                       (long)httpResponse.statusCode);
                [self createFile];
                return;
            }
            NSString *rangeHeader = [headers valueForKey:HTTP_OFFSET];
            if (rangeHeader) {
                long long size = [rangeHeader longLongValue];
                if (size >= [self offset]) {
                    //TODO: we skip file upload, but we mightly verifiy that file?
                    [self setState:Idle];

ERROR Unsupported URL

Hi Im getting this error while uploading.

I'am using iphone 5 v9.2.1.

TUSResumableUpload.m:(151) ERROR: connection did fail due to: Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSUnderlyingError=0x17d758a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL}}, NSLocalizedDescription=unsupported URL}

error: Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSUnderlyingError=0x17d758a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL}}, NSLocalizedDescription=unsupported URL}

Unrecognized selector exception on initWithUploadId:file:delegate:uploadHeaders:finalMetadata:state:uploadUrl:

Hi all, thanks for a nice & simple library. Appreciate the work you save us from reinventing the wheel. I'm running into the follow issue: I tried to initialize a session with the createFromFileUpload...uploadUrl variant and I hit this every time. Looks like it funnels into a private designated initializer... possibly one that isn't implemented?

2019-05-07 17:52:16.335337-0400 Arnor[11925:25862617] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TUSResumableUpload initWithUploadId:file:delegate:uploadHeaders:finalMetadata:state:uploadUrl:]: unrecognized selector sent to instance 0x600002f9df80'
*** First throw call stack:
(
0 CoreFoundation 0x000000010e8291bb __exceptionPreprocess + 331
1 libobjc.A.dylib 0x000000010d3c6735 objc_exception_throw + 48
2 CoreFoundation 0x000000010e847f44 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x000000010e82ded6 forwarding + 1446
4 CoreFoundation 0x000000010e82fda8 _CF_forwarding_prep_0 + 120
5 TUSKit 0x000000010bf7e12e -[TUSResumableUpload initWithUploadId:file:delegate:uploadHeaders:metadata:uploadUrl:] + 622
6 TUSKit 0x000000010bf87252 -[TUSSession createUploadFromFile:headers:metadata:uploadUrl:] + 466

Improve background uploading

For large and resumable uploads it makes sense for TUSKit to support background uploads.

It seems like there should be a way to do this with NSURLSession.

Change repository name

@kvz Can we rename the repository to TUSKit? I realize it's not in the same format as the rest of the repositories, but it will be more familiar to iOS developers. Please consider, thanks.

is it available for swift 4 version?

Hi!
I used to use this library on my objective c project and i like it
is it available for swift version?
if not how to use this library on swift project?

thanks

ERROR: connection requested new body stream, which is currently not supported in example

Running the example with our server setup tus.io compliant and we are receiving

<TUSResumableUpload.m:(115)> Finished upload to PATH/videos/uploads/15/ for fingerprint assets-library://asset/asset.mp4?id=30C691FA-5866-4498-82CB-E95FB600BD74&ext=mp4 2015-04-07 01:46:36.397 TUSKit[207:8879] url: PATH/videos/uploads/15/ 2015-04-07 01:46:36.410 TUSKit[207:8879] <TUSResumableUpload.m:(157)> ERROR: connection requested new body stream, which is currently not supported

- (NSInputStream *)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *)request { TUSLog(@"ERROR: connection requested new body stream, which is currently not supported"); return nil; }

in TUSResumableUpload.m

is where we are getting the error , i'm just not sure why

the uploads on the server are started, but empty.

Any suggestions on how to fix this?

Xcode 6.1.1
and
Example Project

Support Customisation

Recently I had to do some work on an iOS client for a server that use a customised implementation of the TUS protocol.

Which forced me to do some work arsounds on the TUSKit copy that we used.

Therefore I'm asking you to make TUSKit itself more open to customisation. If you'll expose the Header parameter so that the user will be able to pass some extra headers to the POST, HEAD & PATCH requests then less hacking will be forced on the users.

After all while the TUS server protocol is great some people choose to add to it in their implementation which forces us poor client writes to do privet copies... which is the thing to avoid.

I got an Error Unsupported URL

Hi I got an error when uploading
I use iPhone6S Plus ,iOS9.3.2
this is my error message:
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x126aa11b0 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL}}}

my url: http://211.78.245.94:1080

Unrecognized selector exception on initWithUploadId:file:delegate:uploadHeaders:finalMetadata:state:uploadUrl:

Hi guys!

Thanks for the library!

I'm running into the following issue: I tried to restore the upload with restoreUpload: method and I hit this every time. It funnels into a private designated initializer in the declaration of which one of the parameters is missing.

0   CoreFoundation        0x000000011d71d6fb __exceptionPreprocess + 331
1   libobjc.A.dylib       0x000000011ccc9ac5 objc_exception_throw + 48
2   CoreFoundation        0x000000011d73bab4 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3   CoreFoundation        0x000000011d722443 ___forwarding___ + 1443
4   CoreFoundation        0x000000011d724238 _CF_forwarding_prep_0 + 120
5   TUSKit                0x000000011aa96fc9 -[TUSResumableUpload initWithDictionary:delegate:] + 1945
6   TUSKit                0x000000011aa8e9eb -[TUSFileUploadStore loadUploadWithIdentifier:delegate:] + 347
7   TUSKit                0x000000011aa9861d -[TUSSession restoreUpload:] + 205

Handle type workings

This implementation heavily uses NSUInteger which is an apple defined typedef that might change from platform to platform please move to a base type or use your own so that there will be no more compiler workings.

fail stopupload() -> resumeUpload()

Hi, Thank for this library.

stopUpload() -> resumeUpload() is not working.

my project is :

test device : iphone 8

code :
func stopUpload() {
upload?.stop()
}

func resumeUpload() {
upload?.resume()
}

log message :
2019-07-08 11:44:29.112666+0900 TAP[36537:6302131] TUSResumableUpload.m:(620) Resumable upload at https://master.tus.io/files/10c21f95ed62b406b5e071e1caf59bec+2k3EwRWlCXJ0Tg8c.l.vpggfVM7KdgIfKrx76zEvUbmYdu8GmKtnIzXX3F.lxkFtYZcDo39Z5ONfagxf5qvbz__fDBdZf3EQI5Cpzy64box4xLcWNs3d1rDjQWx2y4Rn for 204DFA9D-4313-4007-BA31-2EBAA19DED5B from 1024000 (1024000)
2019-07-08 11:44:29.127635+0900 TAP[36537:6302131] TUSResumableUpload.m:(525) Resuming upload to https://master.tus.io/files/10c21f95ed62b406b5e071e1caf59bec+2k3EwRWlCXJ0Tg8c.l.vpggfVM7KdgIfKrx76zEvUbmYdu8GmKtnIzXX3F.lxkFtYZcDo39Z5ONfagxf5qvbz__fDBdZf3EQI5Cpzy64box4xLcWNs3d1rDjQWx2y4Rn with id 204DFA9D-4313-4007-BA31-2EBAA19DED5B from offset 1024000
2019-07-08 11:45:00.126842+0900 TAP[36537:6303031] Task .<4> finished with error - code: -1001
2019-07-08 11:45:00.127035+0900 TAP[36537:6302131] TUSResumableUpload.m:(561) Error or no response during attempt to upload file, checking state

dead?

is this project dead? there are many deprecated things in here.

Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"

I'm running the sample code exactly as it appears in the repo and one thing I've noticed in the errors that it logs back is that it somehow clips the http: off the the beginning of the url.

I'm running 1.2.1

my input (ip replaced with 0.0.0.0)
//static NSString* const UPLOAD_ENDPOINT = @"http://0.0.0.0:8000/files/";

2016-09-13 12:38:02.662 TUSKit[1201:675510] TUSResumableUpload.m:(335) Created resumable upload at //0.0.0.0:8000/files/7b829af661dfafd516e252d3689e99ba for id 293CA199-A87E-46E9-9ED5-479B91E7123B
2016-09-13 12:38:02.683 TUSKit[1201:675510] TUSResumableUpload.m:(470) Resuming upload to //0.0.0.0:8000/files/7b829af661dfafd516e252d3689e99ba with id 293CA199-A87E-46E9-9ED5-479B91E7123B from offset 0
2016-09-13 12:38:02.686 TUSKit[1201:675510] TUSData.m:(112) TUSData stream opened
2016-09-13 12:38:02.686 TUSKit[1201:675510] TUSData.m:(129) Reading 32768 bytes from 0 to 32768 until 13732856
2016-09-13 12:38:02.690 TUSKit[1201:675510] TUSResumableUpload.m:(496) Error or no response during attempt to upload file, checking state
2016-09-13 12:38:02.711 TUSKit[1201:675510] TUSResumableUpload.m:(397) Unrecoverable error during attempt to check file
2016-09-13 12:38:02.719 TUSKit[1201:675510] error: Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSUnderlyingError=0x159c32960 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}, NSErrorFailingURLStringKey=//0.0.0.0:8000/files/7b829af661dfafd516e252d3689e99ba, NSErrorFailingURLKey=//0.0.0.0:8000/files/7b829af661dfafd516e252d3689e99ba, NSLocalizedDescription=unsupported URL}

Supporting Background Uploads

Hi all, thanks for the great client - it was super easy to get up and running fast.

I saw that TUSKit provides a means for asking iOS for more time to finish its upload task before the app moves to the background, by using the method described in "Executing Finite-Length Tasks" of this Apple doc.

Are there any plans to support true background uploads? i.e. the upload continuing despite the user leaving the app for a while. It seems there are some key limitations with Apple API in attempting to do so:

  • we can't ask a background upload to start from a particular offset in a file, so it will always need to start from the file's beginning (meaning you would have to break the file into chunks if you wanted to start reading bytes from the middle of the original file)
  • the system daemon controlling the background upload task can retry the upload on our behalf, hitting the tus server with another upload request at offset 0, when in fact the tus server has already received some of this file's data, causing a mismatch that rejects our request

I've seen the discussions on how to work around these limitations here:

Does the above seem to capture the latest efforts in supporting background uploads on iOS using tus?

Are there plans for TUSKit to offer more backgrounding support than is currently provided?

Thank you in advance!

Question : Delay from 20 to 30 sec before start upload

Hello,

I start to using this lib : TUSKit 1.4.2 in objective C.

It is working great.
But I see that i have a delay before the upload start : around 20 / 30 sec.
Do you know if it is normal ?

I am uploading to vimeo.
My android app start around 1 / 2 sec uploading.

my code :
`NSURL * applicationSupportURL = [[[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask] firstObject];

TUSUploadStore * uploadStore = [[TUSFileUploadStore alloc] initWithURL:[applicationSupportURL URLByAppendingPathComponent:@"temp_vimeo_tus_upload"]];

self.tusSession = [[TUSSession alloc] initWithEndpoint:[[NSURL alloc] initWithString:upload_url] dataStore:uploadStore allowsCellularAccess:YES];

TUSResumableUpload *upload = [self.tusSession createUploadFromFile:self.mP4Writer.videoPathToUse retry:3 headers:nil metadata:nil uploadUrl:[NSURL URLWithString:upload_url]];


        upload.progressBlock = ^(int64_t bytesWritten, int64_t bytesTotal){
        // Update your progress bar here
        NSLog(@"progress: %llu / %llu", (unsigned long long)bytesWritten, (unsigned long long)bytesTotal);
            
            if([self.delegate respondsToSelector:@selector(vimeouploader_progress:totalBytesExpectedToSend:)]){
            [self.delegate vimeouploader_progress:bytesWritten totalBytesExpectedToSend:bytesTotal];}
        };
            
        upload.resultBlock = ^(NSURL* fileURL){
            // Use the upload url
            NSLog(@"url: %@", fileURL);
            
            if(![self.mP4Writer.wVC.perso_activate isEqualToString:@"true"])
            {
                [self embedVideoOnDomain:self->video_id];
            }
            else
            {
                [self.delegate vimeouploader_succes:@"" methodName:self->video_id];
            }
        };
            
        upload.failureBlock = ^(NSError* error){
            // Handle the error
            NSLog(@"error: %@", error);
            
            if([self.delegate respondsToSelector:@selector(vimeouploader_error:methodName:)])
            {
                  [self.delegate vimeouploader_error:error methodName:@"error"];
            }
        };

        [upload resume];`

Result Block description typo?

In the Readme section discussing the different types of assignable blocks, I believe there is a lil' typo.

Result Block
A block fired when your upload fails.

The above should read, "A block fired when your upload is successful".

Thanks for the library. It's nice : - )

Upload large files > 1GB

Hi !

Will large file uploads > 1 GB be implemented ?

I cannot transfer a 1.5 GB file to an iPad with 1 GB free memory.

Thanks.

Create upload from image data

i plan to be able to upload image after taking a picture from the camera where by the URL path is not attainable, is it possible to create upload with data instead of url?

Compatibility with tus 1.0

tus 1.0 is just around the corner. I would be pleased to see this implementation being updated to support the next version. Most updates are outside the core so only minimal changes are required to maintain comparability. You can find detailed information or get feedback at the according issue tus/tus-resumable-upload-protocol#57-

Upload failed if app is running in the background

I'm using the official example for Tus iOS, uploading a file of approx. 50MB to the Tus test server. If the app is running on the screen the upload is successful.

When I start the upload after few seconds I put the app in the background, and it seems to be working for the next 15-20 seconds then it returns the error:

2019-11-27 10:57:25.797502+0100 TUSKit[22159:529437] Task <61AC3E82-19C2-411F-BDF5-427499B7A96A>.<2> finished with error [-999] Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=http://master.tus.io/files/0b58c6f6c83f7aea04d77deff5099da7+9MHwWbvMSpEPD6j4irvGAZWTPHmEqdg2D6dbOGdxzSz6rINoGB0Sb0uI3WreyL8mqHBOzLOrBpD0Oz.xilW2OHq_PvHCW3q6ToW6Tz9kaYFFu_jl.zFZyP.eLkEA.9P., NSLocalizedDescription=cancelled, NSErrorFailingURLKey=http://master.tus.io/files/0b58c6f6c83f7aea04d77deff5099da7+9MHwWbvMSpEPD6j4irvGAZWTPHmEqdg2D6dbOGdxzSz6rINoGB0Sb0uI3WreyL8mqHBOzLOrBpD0Oz.xilW2OHq_PvHCW3q6ToW6Tz9kaYFFu_jl.zFZyP.eLkEA.9P.}
2019-11-27 10:57:25.797764+0100 TUSKit[22159:529437] TUSResumableUpload.m:(585) Error or no response during attempt to upload file, checking state

Uploading video file using example demo doesn't resume after connection lost.

In the current version of TUSKit and example demo, if you uploading the video file and you lost the network connection for a few seconds and then network appered again then resume upload procedure will try to resending the file forever cusing huge memory leaking and app crash.
I tested with official tus demo server: "https://master.tus.io/files/"

2017-04-19 11:36:21.806 TUSKit[3178:132189] progress: 245760 / 2604768
2017-04-19 11:36:51.908 TUSKit[3178:132189] <TUSResumableUpload.m:(500)> Error or no     response during attempt to upload file, checking state
2017-04-19 11:37:22.234 TUSKit[3178:132189] <TUSResumableUpload.m:(416)> Error or no response during attempt to check file, retrying
2017-04-19 11:37:33.217 TUSKit[3178:132189] <TUSResumableUpload.m:(555)> Resumable upload at https://master.tus.io/files/35f62600f83473960a3c7e8675ac3dfc for 843F3DEC-792C-4693-A1EA- 1AF2F0BC339D from 204800 (204800)
2017-04-19 11:37:33.219 TUSKit[3178:132189] <TUSResumableUpload.m:(474)> Resuming upload to https://master.tus.io/files/35f62600f83473960a3c7e8675ac3dfc with id 843F3DEC-792C-4693-A1EA-1AF2F0BC339D from offset 204800 <--------It's trying to resume forever cusing app to crash!!!!

TUSFileUploadStore fails to save to disk - restoreAllUploads always return empty

Hi everyone,

I'm using the example for iOS, but function [self.tusSession restoreAllUploads] always return an empty array although I know there is pending upload for sure. (I've closed app from app switcher)

As reading code, I guess that's caused by TUSFileUploadStore is linking with app container absolute path while the path itself will be changed per app launching.

Any solution for this? Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.