Showing posts with label iOS. Show all posts
Showing posts with label iOS. Show all posts

Tuesday, 22 May 2018

How to upload files to S3 from iOS app written in Objective C using AWS Cognito identity pool

Background

This post assumes you have setup Cognito identity pool as explained in the previous post -
If not, then please refer the previous post and set that up. Before starting with using this you should have -
  1. Identity pool ID
  2. AWS region where pool and S3 bucket reside
  3. S3 bucket name
We will use above in configuration and implementation that follows.

How to upload files to S3 from iOS app written in Objective C using AWS Cognito identity pool

  • First, go to your pod file and update following dependencies -

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'


target 'TestApp' do
  # Uncomment the next line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!
  # Pods for TestApp


pod 'AWSMobileClient', '~> 2.6.18'  # For AWSMobileClient
pod 'AWSS3', '~> 2.6.18'            # For file transfers
pod 'AWSCognito', '~> 2.6.18'       # For data sync

end

  • Next run "Run pod install --repo-update" from the command line
  • Once you have the dependencies installed we can now write Objective C code to upload a file to S3.


//
//  FileUploader.m
//  TestApp
//
//  Created by Aniket on 22/05/18.
//


#import <Foundation/Foundation.h>


#import "FileUploader.h"
#import <AWSS3/AWSS3.h>
#import <AWSCore/AWSCore.h>




@implementation FileUploader


static AWSS3TransferManager *transferManager;


+ (void) initialize {
    
    if (self == [FileUploader class]) {
        AWSCognitoCredentialsProvider *credentialsProvider = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:AWSRegionUSEast1 identityPoolId:@"us-east-1:f847843f-0162-43c2-b73f-efdc7c69cce2"];
        AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1 credentialsProvider:credentialsProvider];
        [AWSS3TransferManager registerS3TransferManagerWithConfiguration:[[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1 credentialsProvider:credentialsProvider] forKey:s3TransferManagerKey];


        AWSServiceManager.defaultServiceManager.defaultServiceConfiguration = configuration;
                                        
        transferManager = [AWSS3TransferManager S3TransferManagerForKey:s3TransferManagerKey];
    }
    
}


+ (void)uploadFile
{
    
    
    NSURL *uploadingFileURL = [NSURL fileURLWithPath: @"PATH_TO_FILE";
    AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
    
    
    uploadRequest.bucket = s3Bucket;
    int timestamp = [[NSDate date] timeIntervalSince1970];
    uploadRequest.key = [NSString stringWithFormat:@"%@-%d%@",@"testfile",timestamp,@".txt"];
    uploadRequest.body = uploadingFileURL;
    
    [[transferManager upload:uploadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor]
                                                       withBlock:^id(AWSTask *task) {
                                                           if (task.error) {
                                                               if ([task.error.domain isEqualToString:AWSS3TransferManagerErrorDomain]) {
                                                                   switch (task.error.code) {
                                                                       case AWSS3TransferManagerErrorCancelled:
                                                                       case AWSS3TransferManagerErrorPaused:
                                                                           break;
                                                                           
                                                                       default:
                                                                           NSLog(@"Error uploading file to S3: %@", task.error);
                                                                           break;
                                                                   }
                                                               } else {
                                                                   // Unknown error.
                                                                   NSLog(@"Error uploading file to S3: %@", task.error);
                                                               }
                                                           }
                                                           
                                                           if (task.result) {
                                                               AWSS3TransferManagerUploadOutput *uploadOutput = task.result;
                                                               // The file uploaded successfully.
                                                               NSLog(@"uploading file to S3 was successful: %@", uploadOutput);
                                                           }
                                                           return nil;
                                                       }];
    
}
@end


In above code replace the identity pool id and region as per your configuration settings. This is Objective C code, if you want to see Swift or Android - Java please refer https://docs.aws.amazon.com/aws-mobile/latest/developerguide/how-to-integrate-an-existing-bucket.html


Related Links

Saturday, 19 May 2018

How to get the current time in milliseconds

Background

In many scenarios, we need the current time in milliseconds. In this post, we will see various methods to get the time in milliseconds since the UNIX epoch (January 1, 1970 00:00:00 UTC) in various programming languages.

How to get the current time in milliseconds

Following are ways you can get  current time in milliseconds for various programming languages -

  • ActionScript    
    • (new Date()).time
  • C++ 
    • std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count()
  • C#.NET  
    • DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  • Clojure 
    • (System/currentTimeMillis)
  • Excel / Google Sheets*  
    • = (NOW() - CELL_WITH_TIMEZONE_OFFSET_IN_HOURS/24 - DATE(1970,1,1)) * 86400000
  • Go / Golang 
    • time.Now().UnixNano() / 1000000
  • Hive*   
    • unix_timestamp() * 1000
  • Java / Groovy / Kotlin  
    • System.currentTimeMillis()
  • Javascript  
    • new Date().getTime()
  • MySQL*  
    • UNIX_TIMESTAMP() * 1000
  • Objective-C 
    • (long long)([[NSDate date] timeIntervalSince1970] * 1000.0)
  • OCaml   
    • (1000.0 *. Unix.gettimeofday ())
  • Oracle PL/SQL* 
    •  SELECT (SYSDATE - TO_DATE('01-01-1970 00:00:00', 'DD-MM-YYYY HH24:MI:SS')) * 24 * 60 * 60 * 1000 FROM DUAL
  • Perl    
    • use Time::HiRes qw(gettimeofday); print gettimeofday;
  • PHP 
    • round(microtime(true) * 1000)
  • PostgreSQL  
    • extract(epoch FROM now()) * 1000Python  int(round(time.time() * 1000))
  • Qt  
    • QDateTime::currentMSecsSinceEpoch()
  • R*  
    • as.numeric(Sys.time()) * 1000
  • Ruby    
    • (Time.now.to_f * 1000).floor
  • Scala   
    • val timestamp: Long = System.currentTimeMillis
  • SQL Server  
    • DATEDIFF(ms, '1970-01-01 00:00:00', GETUTCDATE())
  • SQLite* 
    • STRFTIME('%s', 'now') * 1000
  • Swift*  
    • let currentTime = NSDate().timeIntervalSince1970 * 1000
  • VBScript / ASP  
    • offsetInMillis = 60000 * GetTimeZoneOffset()
  • WScript.Echo 
    • DateDiff("s", "01/01/1970 00:00:00", Now()) * 1000 - offsetInMillis + Timer * 1000 mod 1000



I recently investigated this as I wanted MicrosoftDateFormat in objective C. We can do this as follows -

  • NSString *date = [NSString stringWithFormat:@"/Date(%lld)/",(long long)([currentTag.firstSeenTime timeIntervalSince1970] * 1000.0)];


NOTE: timeIntervalSince1970 gives you the number of seconds whereas Newtonsoft.Json library (C#) gives it in milliseconds so you need multiple by 1000.0 to get milliseconds.


Related Links



t> UA-39527780-1 back to top