Code Monkey home page Code Monkey logo

afamazons3manager's Introduction

AFNetworking is Deprecated

As of Jan. 17, 2023, AFNetworking is deprecated and there will be no further releases. This repo will remain online in perpetuity as an archive. There are a couple options for continued AFNetworking use:

  1. Copy AFNetworking into your project and compile it directly. This gives you full control over the code.
  2. Fork AFNetworking and use the fork in your dependency manager. There will be no official forks but anyone can fork at any time and can even publish those forks under a different name, in accordance with AFNetworking's license.

Moving forward, Alamofire is the suggested migration path for networking in modern Swift. Anyone who needs help making that migration is welcome to ask on StackOverflow and tag alamofire and afnetworking, or open a discussion on Alamofire's GitHub Discussions regarding any migration issues or missing features.


AFNetworking

Build Status CocoaPods Compatible Carthage Compatible Platform Twitter

AFNetworking is a delightful networking library for iOS, macOS, watchOS, and tvOS. It's built on top of the Foundation URL Loading System, extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.

Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac.

How To Get Started

Communication

  • If you need help, use Stack Overflow. (Tag 'afnetworking')
  • If you'd like to ask a general question, use Stack Overflow.
  • If you found a bug, and can provide steps to reliably reproduce it, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.

Installation

AFNetworking supports multiple methods for installing the library in a project.

Installation with CocoaPods

To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'AFNetworking', '~> 4.0'

Installation with Swift Package Manager

Once you have your Swift package set up, adding AFNetworking as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/AFNetworking/AFNetworking.git", .upToNextMajor(from: "4.0.0"))
]

Note: AFNetworking's Swift package does not include it's UIKit extensions.

Installation with Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate AFNetworking, add the following to your Cartfile.

github "AFNetworking/AFNetworking" ~> 4.0

Requirements

AFNetworking Version Minimum iOS Target Minimum macOS Target Minimum watchOS Target Minimum tvOS Target Notes
4.x iOS 9 macOS 10.10 watchOS 2.0 tvOS 9.0 Xcode 11+ is required.
3.x iOS 7 OS X 10.9 watchOS 2.0 tvOS 9.0 Xcode 7+ is required. NSURLConnectionOperation support has been removed.
2.6 -> 2.6.3 iOS 7 OS X 10.9 watchOS 2.0 n/a Xcode 7+ is required.
2.0 -> 2.5.4 iOS 6 OS X 10.8 n/a n/a Xcode 5+ is required. NSURLSession subspec requires iOS 7 or OS X 10.9.
1.x iOS 5 Mac OS X 10.7 n/a n/a
0.10.x iOS 4 Mac OS X 10.6 n/a n/a

(macOS projects must support 64-bit with modern Cocoa runtime).

Programming in Swift? Try Alamofire for a more conventional set of APIs.

Architecture

NSURLSession

  • AFURLSessionManager
  • AFHTTPSessionManager

Serialization

  • <AFURLRequestSerialization>
    • AFHTTPRequestSerializer
    • AFJSONRequestSerializer
    • AFPropertyListRequestSerializer
  • <AFURLResponseSerialization>
    • AFHTTPResponseSerializer
    • AFJSONResponseSerializer
    • AFXMLParserResponseSerializer
    • AFXMLDocumentResponseSerializer (macOS)
    • AFPropertyListResponseSerializer
    • AFImageResponseSerializer
    • AFCompoundResponseSerializer

Additional Functionality

  • AFSecurityPolicy
  • AFNetworkReachabilityManager

Usage

AFURLSessionManager

AFURLSessionManager creates and manages an NSURLSession object based on a specified NSURLSessionConfiguration object, which conforms to <NSURLSessionTaskDelegate>, <NSURLSessionDataDelegate>, <NSURLSessionDownloadDelegate>, and <NSURLSessionDelegate>.

Creating a Download Task

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];

Creating an Upload Task

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"Success: %@ %@", response, responseObject);
    }
}];
[uploadTask resume];

Creating an Upload Task for a Multi-Part Request, with Progress

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
    } error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
              uploadTaskWithStreamedRequest:request
              progress:^(NSProgress * _Nonnull uploadProgress) {
                  // This is not called back on the main queue.
                  // You are responsible for dispatching to the main queue for UI updates
                  dispatch_async(dispatch_get_main_queue(), ^{
                      //Update the progress view
                      [progressView setProgress:uploadProgress.fractionCompleted];
                  });
              }
              completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                  if (error) {
                      NSLog(@"Error: %@", error);
                  } else {
                      NSLog(@"%@ %@", response, responseObject);
                  }
              }];

[uploadTask resume];

Creating a Data Task

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"%@ %@", response, responseObject);
    }
}];
[dataTask resume];

Request Serialization

Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.

NSString *URLString = @"http://example.com";
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};

Query String Parameter Encoding

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3

URL Form Parameter Encoding

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/x-www-form-urlencoded

foo=bar&baz[]=1&baz[]=2&baz[]=3

JSON Parameter Encoding

[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/json

{"foo": "bar", "baz": [1,2,3]}

Network Reachability Manager

AFNetworkReachabilityManager monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.

  • Do not use Reachability to determine if the original request should be sent.
    • You should try to send it.
  • You can use Reachability to determine when a request should be automatically retried.
    • Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something.
  • Network reachability is a useful tool for determining why a request might have failed.
    • After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out."

See also WWDC 2012 session 706, "Networking Best Practices.".

Shared Network Reachability

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];

[[AFNetworkReachabilityManager sharedManager] startMonitoring];

Security Policy

AFSecurityPolicy evaluates server trust against pinned X.509 certificates and public keys over secure connections.

Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.

Allowing Invalid SSL Certificates

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production

Unit Tests

AFNetworking includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test.

Credits

AFNetworking is owned and maintained by the Alamofire Software Foundation.

AFNetworking was originally created by Scott Raymond and Mattt Thompson in the development of Gowalla for iPhone.

AFNetworking's logo was designed by Alan Defibaugh.

And most of all, thanks to AFNetworking's growing list of contributors.

Security Disclosure

If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email to [email protected]. Please do not post it to a public issue tracker.

License

AFNetworking is released under the MIT license. See LICENSE for details.

afamazons3manager's People

Contributors

abbeycode avatar alexanderedge avatar barrettj avatar bdittmer avatar czivko avatar daskier avatar davidchouinard avatar dmzza avatar evol avatar gertig avatar haseong avatar jverdi avatar marcusficner avatar mattt avatar moshoujingli avatar nxsoftware avatar robertjpayne avatar veritech avatar yaotti 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  avatar  avatar

afamazons3manager's Issues

Sending a file with spaces in the title causes network connection errors

Spaces cause bogus error messages, like:

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x6080000e5500 {NSUnderlyingError=0x60800024da70 "The request timed out.", NSErrorFailingURLStringKey=https://.s3.amazonaws.com/File%20With%20Spaces.zip, NSErrorFailingURLKey=https://.s3.amazonaws.com/File%20With%20Spaces.zip, NSLocalizedDescription=The request timed out.}

and

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo=0x6080000ecd80 {NSUnderlyingError=0x608000059620 "The network connection was lost.", NSErrorFailingURLStringKey=https://.s3.amazonaws.com/File%20With%20Spaces.zip, NSErrorFailingURLKey=https://.s3.amazonaws.com/File%20With%20Spaces.zip, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSLocalizedDescription=The network connection was lost.}

Replacing spaces in the destinationPath with "+" allows it to go through correctly. The resulting file shows up in the S3 console, with spaces intact.

Upload stops when phone goes to sleep and not resuming

First of all awesome library.

I have an issue, I'm uploading a file with the following code:

[s3Manager putObjectWithFile:videoPath
                         destinationPath:destinationPath
                              parameters:nil
                                progress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
                                    float fraction = (totalBytesWritten / (totalBytesExpectedToWrite * 1.0f));
                                    NSLog(@"%f Uploaded", fraction);
                                }
                                 success:^(AFAmazonS3ResponseObject *responseObject) {
                                     //success - do syuff


                                 }

                                 failure:^(NSError *error) {
                                     NSLog(@"Error: %@", error);
                                     return;
                                 }];
        }];

Now the upload takes a long time (a video file), and the app can get into background mode.
When I look at the phone log, after the screen turns off - the % uploaded is getting updated for another 30 seconds or so and then just hangs.
When I get the app back to foreground - it is just stuck... Upload isn't continuing and no error indication.

How can I solve this?

Upload stops at 16%

@interface NetworkManager : NSObject //singleton
{
    AFAmazonS3Client *_s3Client;
}
@end
- (id)init
{
    if( (self = [super init]) )
    {
        _s3Client = [[AFAmazonS3Client alloc] initWithAccessKeyID:ACCESS_KEY secret:ACCESS_SECRET];
        _s3Client.bucket = BUCKET_NAME;
    }
   return self
}
- (void)uploadDataWithFilePath:(NSString *)path videoName:(NSString *)videoName callback:(callbackBlock)callback
{
    [_s3Client postObjectWithFile:path destinationPath:@"/videos/" parameters:nil progress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        NSLog(@"%f%% Uploaded", (totalBytesWritten / (totalBytesExpectedToWrite * 1.0f) * 100));
    }  success:^(id responseObject) {
        callback(YES, nil);
    } failure:^(NSError *error) {
        NSLog(@"%@", error);
        callback(NO, @"There was a problem with uploading the video. Try uploading again.");

    }];

}

Output:

2013-07-15 18:29:33.160 divinenight[3814:907] 1.764420% Uploaded
2013-07-15 18:29:33.163 divinenight[3814:907] 3.528841% Uploaded
2013-07-15 18:29:33.165 divinenight[3814:907] 5.293261% Uploaded
2013-07-15 18:29:33.166 divinenight[3814:907] 7.049712% Uploaded
2013-07-15 18:29:33.227 divinenight[3814:907] 7.057681% Uploaded
2013-07-15 18:29:33.229 divinenight[3814:907] 7.232572% Uploaded
2013-07-15 18:29:33.247 divinenight[3814:907] 7.389802% Uploaded
2013-07-15 18:29:33.284 divinenight[3814:907] 7.547031% Uploaded
2013-07-15 18:29:33.298 divinenight[3814:907] 7.887122% Uploaded
2013-07-15 18:29:33.370 divinenight[3814:907] 8.437427% Uploaded
2013-07-15 18:29:33.379 divinenight[3814:907] 8.594656% Uploaded
2013-07-15 18:29:33.397 divinenight[3814:907] 8.751885% Uploaded
2013-07-15 18:29:33.408 divinenight[3814:907] 8.822101% Uploaded
2013-07-15 18:29:33.414 divinenight[3814:907] 8.987731% Uploaded
2013-07-15 18:29:33.432 divinenight[3814:907] 9.144960% Uploaded
2013-07-15 18:29:33.451 divinenight[3814:907] 9.380806% Uploaded
2013-07-15 18:29:33.479 divinenight[3814:907] 9.538035% Uploaded
2013-07-15 18:29:33.486 divinenight[3814:907] 9.695265% Uploaded
2013-07-15 18:29:33.526 divinenight[3814:907] 10.088340% Uploaded
2013-07-15 18:29:33.545 divinenight[3814:907] 10.245569% Uploaded
2013-07-15 18:29:33.563 divinenight[3814:907] 10.463753% Uploaded
2013-07-15 18:29:33.585 divinenight[3814:907] 10.586521% Uploaded
2013-07-15 18:29:33.596 divinenight[3814:907] 10.699597% Uploaded
2013-07-15 18:29:33.604 divinenight[3814:907] 10.856828% Uploaded
2013-07-15 18:29:33.638 divinenight[3814:907] 11.014057% Uploaded
2013-07-15 18:29:33.652 divinenight[3814:907] 11.171287% Uploaded
2013-07-15 18:29:33.661 divinenight[3814:907] 11.328517% Uploaded
2013-07-15 18:29:33.683 divinenight[3814:907] 11.564362% Uploaded
2013-07-15 18:29:33.702 divinenight[3814:907] 11.800206% Uploaded
2013-07-15 18:29:33.730 divinenight[3814:907] 11.957436% Uploaded
2013-07-15 18:29:33.737 divinenight[3814:907] 12.114666% Uploaded
2013-07-15 18:29:33.769 divinenight[3814:907] 12.350511% Uploaded
2013-07-15 18:29:33.780 divinenight[3814:907] 12.350942% Uploaded
2013-07-15 18:29:33.783 divinenight[3814:907] 12.507740% Uploaded
2013-07-15 18:29:33.814 divinenight[3814:907] 12.664970% Uploaded
2013-07-15 18:29:33.826 divinenight[3814:907] 12.822201% Uploaded
2013-07-15 18:29:33.835 divinenight[3814:907] 13.058044% Uploaded
2013-07-15 18:29:33.868 divinenight[3814:907] 13.293889% Uploaded
2013-07-15 18:29:33.877 divinenight[3814:907] 13.451118% Uploaded
2013-07-15 18:29:33.901 divinenight[3814:907] 13.608350% Uploaded
2013-07-15 18:29:33.937 divinenight[3814:907] 14.001423% Uploaded
2013-07-15 18:29:33.950 divinenight[3814:907] 14.115362% Uploaded
2013-07-15 18:29:33.965 divinenight[3814:907] 14.237268% Uploaded
2013-07-15 18:29:33.984 divinenight[3814:907] 14.473113% Uploaded
2013-07-15 18:29:34.000 divinenight[3814:907] 14.630343% Uploaded
2013-07-15 18:29:34.016 divinenight[3814:907] 14.787573% Uploaded
2013-07-15 18:29:34.033 divinenight[3814:907] 14.944802% Uploaded
2013-07-15 18:29:34.049 divinenight[3814:907] 15.102032% Uploaded
2013-07-15 18:29:34.064 divinenight[3814:907] 15.259263% Uploaded
2013-07-15 18:29:34.083 divinenight[3814:907] 15.416492% Uploaded
2013-07-15 18:29:34.097 divinenight[3814:907] 15.573722% Uploaded
2013-07-15 18:29:34.115 divinenight[3814:907] 15.730951% Uploaded
2013-07-15 18:29:34.132 divinenight[3814:907] 15.879782% Uploaded
2013-07-15 18:29:34.149 divinenight[3814:907] 16.045410% Uploaded
2013-07-15 18:29:34.168 divinenight[3814:907] 16.202641% Uploaded
2013-07-15 18:29:34.181 divinenight[3814:907] 16.438486% Uploaded
2013-07-15 18:29:34.217 divinenight[3814:907] 16.595715% Uploaded
2013-07-15 18:29:34.229 divinenight[3814:907] 16.752947% Uploaded
Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x1d9c70e0 {NSErrorFailingURLStringKey=http://divinenight.s3.amazonaws.com/videos/, NSErrorFailingURLKey=http://divinenight.s3.amazonaws.com/videos/, NSLocalizedDescription=The request timed out., NSUnderlyingError=0x1d9c83e0 "The request timed out."}

Repeated the process, same outcome every time.

NSURLErrorDomain Code=-1012

I am getting NSURLErrorDomain Code=-1012 error when I try to upload a file to amazon s3. Am I missing something?
Also I needed to change the init code in order to make this class at least working.

- (id)initWithAccessKeyID:(NSString *)accessKey
                   secret:(NSString *)secret
{
    self = [self init];
    if (!self) {
        return nil;
    }
    self.operationQueue=[NSOperationQueue mainQueue];
    self.requestSerializer = [AFAmazonS3RequestSerializer serializer];
    self.responseSerializer = [AFXMLParserResponseSerializer serializer];
    [self.requestSerializer setAccessKeyID:accessKey secret:secret];

    return self;
}

Create folder

I'm figuring out how could I handle folder creation with AFAmazonS3Client.
At this point I can upload files to my bucket (in root). I tried to change my destination path (e.g @"/newFolder/") but I get an error.

Is it possible ?

`putObjectWithFile:` returns NSURLErrorDomain -1012 with AFNetworking 2.5.3 + AFAmazonS3Manager 3.2.1

I started getting NSURLErrorDomain -1012 on every putObjectWithFile: call (Xcode 6.3.1 + Swift + iOS 8.3 on iPhone 6) when I upgraded AFNetworking to 2.5.3.

File upload failed with error: Error Domain=NSURLErrorDomain Code=-1012
"The operation couldn’t be completed. (NSURLErrorDomain error -1012.)

With AFNetworking 2.5.2 it works fine. I'm using AFAmazonS3Manager and AFNetworking with CocoaPods 0.36.3 along with these pods:

Using AFAmazonS3Manager (3.2.1)
Using AFNetworking (2.5.2)
Using Firebase (2.2.2)
Using SDWebImage (3.7.2)
Using SVProgressHUD (1.1.3)
Using UIAlertController+Blocks (0.9)

Compiler warning: "Implicit conversion from enumeration type..."

I'm getting this when building my project that uses AFAmazonS3Client

.../Pods/AFAmazonS3Client/AFAmazonS3Client/AFAmazonS3Manager.m:223:33: Implicit conversion from enumeration type 'enum NSURLCacheStoragePolicy' to different enumeration type 'NSURLRequestCachePolicy' (aka 'enum NSURLRequestCachePolicy')

Can't change content type of PUT file from octet/stream to image/jpeg

I'm sending images to s3 like this:

[[[VS3 sharedVS3] s3Manager]
     putObjectWithFile:fileName
     destinationPath:remotePath
     parameters:nil
     progress:nil

and this works, but the files seem to be the default octet/stream on s3, which is not desirable.
so we try to set the Content-type header to image/jpeg like this:

[[[VS3 sharedVS3] s3Manager]
     putObjectWithFile:fileName
     destinationPath:remotePath
     parameters:@{@"Content-Type":@"image/jpeg"}
     progress:nil

and that works (to set the header), but now we get 403 from s3:

The request signature we calculated does not match the signature you provided. 
Check your key and signing method

<StringToSign>PUT

image/jpeg
Fri, 29 May 2015 06:03:06 GMT
/vnimages/uploads/2015/05/29/11/E29128D6-FD26-4B0E-9268-BB3A04B13173.jpg</StringToSign>

Seems like the Content-Type parameter is missing from the signing of the request?

I see in AFAmazonS3Manager::putObjectWithFile that it does this to get the signed request:

request = [self.requestSerializer requestWithMethod:method URLString:[[self.baseURL URLByAppendingPathComponent:destinationPath] absoluteString] parameters:nil error:nil];

which shows that the parameters passed to putObjectWithFile never get to requestBySettingAuthorizationHeadersForRequest in the requestSerializer. But, changing that nil to parameters doesn't fix it for me.

Complier Warning: "Auto property synthesis will not synthesize property"

When using Xcode 6.3 Beta 3 AFAmazonS3Manager.h generates a compiler warning as follows:

Auto property synthesis will not synthesize property 'requestSerializer'; it will be implemented by its superclass, use @dynamic to acknowledge intention

I've made a pull request #84 b27c34d that seems to take care of the issue by adding the specified @dynamic call in the @implementation, but someone should probably check to make sure that's the correct approach.

Thanks,
daSkier

responseObject is null

I'm trying to upload a wav file to my bucket.
The upload works fine but in success block I've got only @"Upload Complete" and a responseObject that is null.
What's wrong?

Add meaningful response objects

Amazon S3's HTTP responses have no payload, but the responses are treated as XML with the AFXMLParserResponseSerializer. Unfortunately, this buries the useful information included in the response: the URL of the resulting file, and the ETag (MD5 hash) of the file.

It would make sense to add a dedicated AFAmazonS3ResponseSerializer, the same way requests have a special handler. This should return a new class AFAmazonS3ResponseObject, which encapsulates the raw header info.

Support passing NSData instead of file paths to put/post methods in 1.x

In many cases, the raw NSData is more accessible than a file path, for example, when taking photos with the camera. So currently you have to save the file to disk just to pass the file url to the method, which then reads the file in so it can create an NSData object. Would you support a pull request that allowed passing the NSData in manually?

Outdated Documentation (How to use this library?)

I don't want to come off as the guy who just takes it for granted, but just to let you know I've been trying to get this to work for the last several hours and still couldn't. I'm not an idiot and i've never had this severe issue when integrating 3rd party libraries before.

What I've figured out so far is that I think the example code in Readme is inconsistent with how the code is actually implemented--even the filenames are different.

I'm guessing there used to be one AFAmazonS3Client but now it's separated into AFAmazonS3Manager and AFAmazonS3RequestSerializer. Even after figuring that out I am having hard time actually using the library.

Basically I have no idea what values I should be passing for what parameters. I've done my homework and searched around the web for examples of how people use it but they're all outdated. Could someone please explain how to use this?

nil value reading plist file from document folder after download from Amazon S3

I created an app that download a plist file from Amazon S3.

-(void) getFile:(NSString *)fileName{
    self.s3Manager = [[AFAmazonS3Manager alloc] initWithAccessKeyID:@"..." secret:@"..."];
    self.s3Manager.requestSerializer.region = AFAmazonS3SAEast1Region;
    self.s3Manager.requestSerializer.bucket = @"verba";

    NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    documentsPath = [documentsPath stringByAppendingPathComponent:fileName];

    NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:documentsPath append:NO];

    [self.s3Manager getObjectWithPath:@""
                         outputStream:stream
                             progress:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
         NSLog(@"%f%% Downloaded", (totalBytesRead / (totalBytesExpectedToRead * 1.0f) * 100));
    } success:^(id responseObject) {
         NSLog(@"Download Complete");
    } failure:^(NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}

Then I checked if the plist file was in document folder. And it was. So I tried to open plist file and the result was nil:

-(NSString*) loadListName:(NSString*)fileName{
    NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString* filePath = [documentsPath stringByAppendingPathComponent:fileName];

    NSDictionary *temp;
    if ([[NSFileManager defaultManager] fileExistsAtPath: filePath]){
        temp = [NSDictionary dictionaryWithContentsOfFile:filePath];
    } else {
        NSLog(@"File not found.");
    }

    NSString *listName = [temp objectForKey:@"name"];

    return listName;
}

So I tried to add plist file manually. I downloaded and copied it to the documents folder and then dictionaryWithContentsOfFile could open the file. So I suppose that plist file was corrupted when I download the file using AFAmazonS3Client.

What I am doing wrong ?

AFNetworking 2.0 Support

Hi, Is there any plan to support AFNetworking 2.0 in the near future?

Thanks in advance for your answer.

uploading with public-read permissions

I'm trying to upload a file with public-read permissions but have been unsuccessful. Here is the call I'm trying to do to add the acl to the header:

[s3Manager.requestSerializer setValue:@"public-read" forHTTPHeaderField:@"x-amz-acl"];

Files uploaded using PUT contain the whole multipart body

Each file uploaded to S3 contains the whole multipart body as its content.

This could be even an AFNetworking issue, as I found a Stack Overflow question where the author has the exact same issue, but using his own S3 handling classes.

Example code:

AFAmazonS3Manager *s3 = [[AFAmazonS3Manager alloc] initWithAccessKeyID:@"access key" secret:@"secret"];

NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *filePath = [dirPaths[0] stringByAppendingPathComponent:@"test.txt"];

[@"test test test" writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

[s3 putObjectWithFile:filePath destinationPath:@"test.txt" parameters:nil progress:nil success:^(id responseObject) {
    NSLog(@"Uploaded!");
} failure:^(NSError *error) {
    NSLog(@"Error: %@", error);
}];

Resulting file, as downloaded from S3:

--Boundary+FEC9EABEC1FD2A44
Content-Disposition: form-data; name="key"

test.txt
--Boundary+FEC9EABEC1FD2A44
Content-Disposition: form-data; name="file"; filename="test.txt"
Content-Type: text/plain

test test test
--Boundary+FEC9EABEC1FD2A44--

Confusing on how to save files to subfolders

My instinct for uploading a file to a folder was to set the destination path, however that did not appeared to work, instead I ended up having to:

[self.s3Manager postObjectWithFile:path
destinationPath:@"/"
parameters:@{@"key": @"/subfolder/subfolder/filename"}
progress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
}
success:^(id responseObject) {
}
failure:^(NSError *error) {
}];

AFAmazonS3Client cancel download

I think there should be a way to cancel download initiated with the -[AFAmazonS3Manager getObjectWithPath:progress:success:failure:].

putObjectWithFile Authorization problem

If I use putObjectWithFile with some x-amz headers, for example

x-amz-acl: public-read

The Authorization header is calculated wrong. Because x-amz-acl is not included in the calculation. Another header missing from the calculation is Content-Type.

Here is another question. If I want to putObject with NSData, it seems that I have write my own method.

Thanks!

Large Uploads

Added this to our app the other day and putObjectWithFile works great to send files to our S3 bucket, at least if the files are under 100MB. Ours is a video app and so quite often the upload will be larger.

What happens is when the files get too large (I was using 125MB zip) is that the app starts eating up 128MB chunks of memory until the OS shuts it down. This happens sometime after the call to putObjectWithFile but before the progress callback ever happens.

Can't upload

I got the following error message:

Error: Error Domain=NSURLErrorDomain Code=-1021 "request body stream exhausted"

The code to upload is the one in your readme file.

Uploading multiple images

How would I go about that? It seems to me, it's only possible to upload one image at a time?

UPDATE:

I think I got ahead of myself before. I can't even upload a single image. Would it be possible to provide some dummy code displaying how to upload a single UIImage? And if possible, how to upload multiple UIImages?

Setting endpoint to request

I have noticed that using AFAmazonS3Client I can only download successfully if I try it with files where the endpoint is the default US_WEST but in my case I have a lot of files stored in the tokyo one so need to change the endpoint for successful download but how can I do this with this client?

Uploading .mov file getting corrupted

I am trying to upload a .mov file to s3 but after uploading it to s3 and then downloading it to my computer the Quicktime player says: "QuickTime Player can't open "file.mov" because the movie's file format isn't recognized." Here is the code:

      AFAmazonS3Client *s3Client = [[AFAmazonS3Client alloc] initWithAccessKeyID:@"ID" secret:@"SECRET"];
        s3Client.bucket = @"bucket";
        [s3Client putObjectWithFile:video.filePath parameters:nil progress:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
            NSLog(@"%f%% Uploaded", (totalBytesWritten / (totalBytesExpectedToWrite * 1.0f) * 100));
        } success:^(id responseObject) {
             NSLog(@"Upload Complete");                   
         } failure:^(NSError *error) {
              NSLog(@"Error: %@", error);
          }];

Please help. Thank you.

README example out of data

The example in the README doesn't even compile.

AFAmazonS3Manager *s3Manager = [[AFAmazonS3Manager alloc] initWithAccessKeyID:@"..." secret:@"..."];
s3Manager.region = AFAmazonS3USWest1Region; // ERROR! property region not found on object of type 'AFAmazonS3Manager'
s3Manager.bucket = @"my-bucket-name"; // ERROR! property bucket not found on object of type 'AFAmazonS3Manager'

It seems by looking at the implementation that it should be using something like requestSerializer.region.

Can someone point to an example that actually works?

timing out after uploading 140-200k

Thanks for sharing this code. I'm trying to test it out using your example code and it's hanging during the upload. It quickly uploads a variable percentage, seems to be working but no additional information written to the log, and then eventually times out. The percentage varies a bit from file to file, but always seems to be around 200k.

Have you run into this?

Certificate issue

I get the following error, while trying to upload a file to Amazon

here is the code,

s3Client = [[AFAmazonS3Client alloc] initWithAccessKeyID:@"mykey" secret:@"mysecretkey"];
s3Client.bucket = @"media.mysite.com";

[s3Client postObjectWithFile:video.assetPath destinationPath:@"/media/videos/" parameters:nil progress:

 ^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite){

     DLog(@"%f%% Uploaded", (totalBytesWritten / (totalBytesExpectedToWrite * 1.0f) * 100));
 }

                     success:^(id responseobject){

                         DLog(@"Success");
                         [self deleteAsset:video];

                     }failure:^(NSError* error){

                          DLog(@"Failed %@", error);
                         [self updateVideoAsset:video.assetID key:@"uploadStatus" value:[NSNumber numberWithInt:ESUploadNotStarted]];
                     }];

The certificate for this server is invalid. You might be connecting to a server that is pretending to be “media.myserver.com.s3.amazonaws.com” which could put your confidential information at risk

Accept NSData instead of just file paths?

I have the need to post data I already have in memory (UIImage). Writing it to a file just to post it doesn't seem to make much sense. It seems like it would be a good add.

If you agree, I can make the additions and submit a pull request.

Security concerns?

We're building an iOS app that needs to store content on S3. We've been using AFAmazonS3Manager for testing purposes for the past few months and have loved it. However, we were under the impression that it is very bad practice to include our access key and secret hard-coded into the client app. Is this meant to be baked into the final product, or a framework for getting apps up and running, intended to be the stepping stone before graduating to something like Amazon Cognito?

Thanks!

On OSX: The request timed out

I'm seeing timeouts that look similar to #1 except that I'm using AFNetworking 1.2.0 on OSX 10.8 and connecting over wifi, so I don't think the same limitation seen over 3G applies.
Example:

    AFAmazonS3Client *s3Client = [[AFAmazonS3Client alloc] initWithAccessKeyID:AWS_ACCESS_KEY secret:AWS_SECRET_KEY;
    s3Client.bucket = BUCKET_NAME;
    [s3Client postObjectWithFile:FILENAME_TO_UPLOAD
                 destinationPath:s3Key
                      parameters:nil
                        progress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
                            NSLog(@"%f%% Uploaded", (totalBytesWritten / (totalBytesExpectedToWrite * 1.0f) * 100));
                        }
                         success:^(id responseObject) {
                             NSLog(@"Upload Complete");
                         }
                         failure:^(NSError *error) {
                             NSLog(@"Error: %@", error);
                         }
     ];

Any advice on how to troubleshoot?

bucket should not be a @property

AFAmazonS3Client has a property called bucket. This makes it very inconvenient to use a single client object with more than one bucket at a time. Is there a reason why bucket is a property and not a parameter for methods which are creating NSURLRequests? I can only assume that bucket is a property instead of a parameter so that the existing methods of AFHTTPClient can be used (they do not have a bucket parameter).

One could argue that one AFAmazonS3Client should be used per bucket which is not a good argument in my opinion.

What do you think about a AFAmazonS3RequestOperation class that let's you specify a bucket name?

I would gladly work on that and send you a pull request...

AFNetworking (~> 1.0) required

Hello,

I added 'AFAmazonS3Client' to my podfile

pod 'AFAmazonS3Client', '~> 0.3.0'

However when I update my pod:

[!] Unable to satisfy the following requirements:

  • AFNetworking (~> 2.3.1) required by Podfile
  • AFNetworking/Serialization required by AFNetworking (2.3.1)
  • AFNetworking/Security required by AFNetworking (2.3.1)
  • AFNetworking/Reachability required by AFNetworking (2.3.1)
  • AFNetworking/NSURLConnection required by AFNetworking (2.3.1)
  • AFNetworking/NSURLSession required by AFNetworking (2.3.1)
  • AFNetworking/Serialization required by AFNetworking/NSURLConnection (2.3.1)
  • AFNetworking/Reachability required by AFNetworking/NSURLConnection (2.3.1)
  • AFNetworking/Security required by AFNetworking/NSURLConnection (2.3.1)
  • AFNetworking/Serialization required by AFNetworking/NSURLSession (2.3.1)
  • AFNetworking/Reachability required by AFNetworking/NSURLSession (2.3.1)
  • AFNetworking/Security required by AFNetworking/NSURLSession (2.3.1)
  • AFNetworking (~> 1.0) required by AFAmazonS3Client (0.3.0)

I read the AFAmazonS3Client.podspec and I see it's compatible with AFNetworking 2.0 ¿? I try "pod repo update" but It doesn't work.

AWS S3 PUT Request Question

I've literally spent the last 3 - 4 hours trying to do what should have been the simplest of tasks using AFAmazonS3Client.

When I use postObjectWithFile AWS S3 responds that POST isn't a supported method. When I switch over to putObjectWithFile the file is uploaded but isn't recognised as AFAmazonS3Client prepends the multipart data to the file.

I'll be honest, writing a digital SLR remote app today using a poorly documented Canon SDK has been less frustrating than using AFAmazonS3Client.

How to cancel AFAmazonS3Manager uploading process

Hi,

I am use AFAmazonS3Manager to upload files to S3 bucket by referencing the code in usage example. But How to cancel a uploading process? And can I delete a file from S3 using AFAmazonS3Manager? How?

Thanks.

SignatureDoesNotMatch

Always response this error:
The request signature we calculated does not match the signature you provided. Check your key and signing method.

I tried aws iOS sdk, it works well, but it's too large for me...

Anybody knows why this happend?

Thanks~

SignatureDoesNotMatch

I know that this issue was closed, but I'm still seeing? Is anyone else having this?

Getting 501 error when uploading to S3

I am using AFAmazonS3Manager to upload images to S3. Here is my setup:

        singleton.s3Manager = [[AFAmazonS3Manager alloc] initWithAccessKeyID:@"XXX" secret:@"XXX"];
        singleton.s3Manager.requestSerializer.bucket = @"XXX";

I then upload as follows:

    [self.s3Manager putObjectWithFile:localFile destinationPath:@"images/file" parameters:nil progress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    } success:^(id responseObject) {
    } failure:^(NSError *error) {
        NSLog(@"Error: %@", error);
    }];

But the upload fails with error

error Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unimplemented (501)" UserInfo=0x1704e7a80

I saw some people suggesting adding Content-Length header but not sure where should I add it. Thanks.

percent encoding in URL

If you have some special characters in your object's key. The Authentication calculation is wrong.

There are actually two problems,

  1. URLByAppendingPathComponent already encodes special character, so the function AFPathByEscapingSpacesWithPlusSigns() is not needed.
  2. In AFAWSSignatureForRequest, when you get the path from request.URL.path. The % encode in the URL is decoded. So the calculation of Authenticaton header is wrong.

AFStreamingMultipartFormData strip metadata from images while making a "PUT" Request

I am trying to upload an Image using
putObjectWithFile:destinationPath:
parameters:
progress:
success:
failure:

method.
I am able to download the same image from amazon S3 by creating a signed URL request,but i am not able to open it using Preview.app on MAC OS X.
Upon introspection I found out that the following data gets added to the top of the image while uploading it.

2D 2D 42 6F 75 6E 64 61 72 79 2B 30 44 32 36 45 --Boundary+0D26E
39 46 43 37 36 39 31 31 36 37 46 0D 0A 43 6F 6E 9FC7691167F..Con
74 65 6E 74 2D 44 69 73 70 6F 73 69 74 69 6F 6E tent-Disposition
3A 20 66 6F 72 6D 2D 64 61 74 61 3B 20 6E 61 6D : form-data; nam
65 3D 22 6B 65 79 22 0D 0A 0D 0A 74 68 6F 72 2E e="key"....thor.
6A 70 67 0D 0A 2D 2D 42 6F 75 6E 64 61 72 79 2B jpg..--Boundary+
30 44 32 36 45 39 46 43 37 36 39 31 31 36 37 46 0D26E9FC7691167F
0D 0A 43 6F 6E 74 65 6E 74 2D 44 69 73 70 6F 73 ..Content-Dispos
69 74 69 6F 6E 3A 20 66 6F 72 6D 2D 64 61 74 61 ition: form-data
3B 20 6E 61 6D 65 3D 22 66 69 6C 65 22 3B 20 66 ; name="file"; f
69 6C 65 6E 61 6D 65 3D 22 74 68 6F 72 2E 6A 70 ilename="thor.jp
67 22 0D 0A 43 6F 6E 74 65 6E 74 2D 54 79 70 65 g"..Content-Type
3A 20 69 6D 61 67 65 2F 6A 70 65 67 0D 0A 0D 0A : image/jpeg....

The normal image HeX content starts after this chunk.
I can open the same image using GraphicConverter app.
So my question is ,Is that metadata at the top necessary?
Is this normal behavior?
If so is there a way to strip that out before adding this to httpbodystream?
I am new to AFNetworking .Any pointers would be more than welcome.

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.