How to send multiple images Amazon S3 Server ios objective-c - objective-c

I am trying to upload images to Amazon S3 using this logic:
- (void)uploadImageToS3: (UIImage *)image {
imageData = UIImageJPEGRepresentation(image, 0.7);
AWSS3GetPreSignedURLRequest *getPreSignedURLRequest = [AWSS3GetPreSignedURLRequest new];
getPreSignedURLRequest.bucket = #"dummyimages";
getPreSignedURLRequest.key = #"test.jpg";
getPreSignedURLRequest.HTTPMethod = AWSHTTPMethodPOST;
getPreSignedURLRequest.expires = [NSDate dateWithTimeIntervalSinceNow:3600];
NSString *fileContentTypeString = #"text/plain";
getPreSignedURLRequest.contentType = fileContentTypeString;
[[[AWSS3PreSignedURLBuilder defaultS3PreSignedURLBuilder] getPreSignedURL:getPreSignedURLRequest] continueWithBlock:^id(AWSTask *task) {
if (task.error) {
NSLog(#"Error: %#", task.error);
} else {
NSURL *presignedURL = task.result;
NSLog(#"upload presignedURL is \n%#", presignedURL);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:presignedURL];
request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
[request setHTTPMethod:#"PUT"];
[request setValue:fileContentTypeString forHTTPHeaderField:#"Content-Type"];
NSURLSessionUploadTask *uploadTask = [[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"Upload errer: %#", error);
}
NSLog(#"Done");
}];
[uploadTask resume];
}
return nil;
}];
}
I am getting an error like this:
'NSInternalInconsistencyException', reason: 'The service configuration is nil. You need to configure Info.plist or set defaultServiceConfiguration before using this method.
could please help this issue
Thanks

Have a look at http://docs.aws.amazon.com/mobile/sdkforios/developerguide/setup.html , in the section Preparing iOS 9 Apps.

You need to configure your service configuration in the class that is responsible for managing the Amazon Identity.
If you are using the newer version of MobileHub then the AWS constants
are configured in your info.plist and you need to check this
If you are using an older version MobileHub then the constants file is AWSConfiguration.
The class responsible for managing identity is AWSIdentityManager where the function that configures the service is
- (AWSTask *)initializeClients:(NSDictionary *)logins
If you are not using MobileHub you need to implement something similar in your own identity manager.

Add below code line for info.Plist file
<key>NSExceptionDomains</key>
<dict>
<key>amazonaws.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
<key>amazonaws.com.cn</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
</dict>

Related

Get details from plist file with objective-c

Here is my problem.
I can't seem to figure out how to access the "Details" key in the same level as the "Name" key once search for a specific name key. Maybe I'm missing something?
I know you can get "Details" via [dict objectForKey:#"Details"] but I'm not sure how to get the one on the same levels as the one that was searched for.
Code:
- (IBAction)ScoringButtonView:(id)sender {
ScoringViewController *svController = [[ScoringViewController alloc] initWithNibName:#"ScoringView" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:svController animated:YES];
UIButton *scoringButton = (UIButton*)sender;
NSLog(#"Scoring is %# ", scoringButton.currentTitle);
svController.ScoringName = scoringButton.currentTitle;
NSString *path = [[NSBundle mainBundle] pathForResource:#"Scoring" ofType:#"plist"];
NSArray *plistData = [NSArray arrayWithContentsOfFile:path];
for (NSDictionary *dict in plistData) {
if ([[dict objectForKey:#"Name"] isEqualToString:scoringButton.currentTitle]) {
NSLog(#"Scoring == %# ", scoringButton.currentTitle);
// svController.ScoringInfo =
}
}
plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>Name</key>
<string>Standard</string>
<key>Details</key>
<string>dagsdfgds</string>
</dict>
<dict>
<key>Name</key>
<string>Advanced</string>
<key>Details</key>
<string>gfdsgdfsgdsfg</string>
</dict>
</array>
</plist>
I'm not sure what the confusion is. You already know how to get the value for the Name key. Getting the value for the Details key is the same:
for (NSDictionary *dict in plistData) {
if ([dict[#"Name"] isEqualToString:scoringButton.currentTitle]) {
NSString *details = dict[#"Details"];
}
}
Note how I used modern Objective-C syntax instead of the old style use of objectForKey:.
//This method should work fine
//Enumeration method is better than for loop
NSString *filePath = [[NSBundle mainBundle] pathForResource:#“LanguageList” ofType:#"json"];
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSJSONReadingAllowFragments error:NULL];
NSError *error = nil;
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:[myJSON dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
[dict[#"result"] enumerateObjectsUsingBlock:^(id _Nonnull objList, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(#“Values %#”,obj);
*stop = YES;
}
}];

How to work Synchronous and Asynchronous web in obj c [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm new for development learning to parsing the data and how to work with synchronous and asynchronous requests.
NSString *url=#"http://content.guardianapis.com/search?api-key=test";
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSError *error=nil;
NSURLResponse *response;
NSData *content=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *string=[[NSString alloc]initWithData:content encoding:NSUTF8StringEncoding];
NSLog(#"response %#",string);
I receive a warning at the sendSynchronousRequest line. How do I process this asynchronously web request and get the response data. Explain difference of both.
Two separate issues here.
First, the request should be asynchronous and use NSURLSession. For example:
NSURL *url = [NSURL URLWithString:#"http://content.guardianapis.com/search?api-key=test"];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(#"%#", error);
return;
}
NSError *parseError;
NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (responseObject) {
NSLog(#"%#", responseObject);
dispatch_async(dispatch_get_main_queue(), {
// if you want to update your UI or any model objects,
// do that here, dispatched back to the main queue.
});
} else {
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"problem parsing response, it was:\n%#", string);
}
}];
[task resume];
// but do not try to use `data` here, as the above runs asynchronously
// do everything contingent upon this request _inside_ the completion
// handler above
Note, when you get the JSON response, you can parse that with NSJSONSerialization, as shown above.
Nowadays, using http for requests is frowned upon because it's not secure. You generally should use https. And NSURLSession will enforce this, returning an error if you try to use http. But if you want to force it to permit an insecure http request, you have to update your info.plist with an entry that looks like:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>guardianapis.com</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Include to specify minimum TLS version-->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
So, go to your info.plist, control-click on it and choose "Open As" ... "Source Code" and then add the above into it. See https://stackoverflow.com/a/31254874/1271826 for more information.

Why won't this WebView load an external URL with string?

I'm using this project to get me started with the WebKit framework under OSX.
It loads resources locally, and I've been able to get it to work. However, when I alter awakeFromNib to load from a URL string like http://www.example.com/index.html It doesn't work, the view is blank, even though this is a valid URL.
Original:
- (void)awakeFromNib {
WebPreferences *prefs = [webView preferences];
[prefs _setLocalStorageDatabasePath:#"~/Library/WebViewExample/LocalStorage"];
NSString *resourcesPath = [[NSBundle mainBundle] resourcePath];
NSString *htmlPath = [resourcesPath stringByAppendingString:#"/htdocs/640x480_naked.html"];
[[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:htmlPath]]];
}
Modified for external URL:
- (void)awakeFromNib {
WebPreferences *prefs = [webView preferences];
[prefs _setLocalStorageDatabasePath:#"/tmp"];
NSString *urlText = #"http://www.example.com/index.html";
[[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlText]]];
}
What could be wrong?
Thanks to the comment and link from #danh. This solved it for me.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>example.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
</dict>
</dict>

Service launches my application again and hangs the requesting application

I'm trying to make my program provide a service to look up words. It works when I drag some text onto the icon but when I try to use the menu item it opens another instance of the application, freezes the application I sent the request from for about 30 seconds and then doesn't execute the method it was supposed to.
Here is my method:
- (void)serviceQuery:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error {
// Test for strings on the pasteboard.
NSArray *classes = [NSArray arrayWithObject:[NSString class]];
NSDictionary *options = [NSDictionary dictionary];
if (![pboard canReadObjectForClasses:classes options:options]) {
*error = NSLocalizedString(#"Error: couldn't encrypt text.",
#"pboard couldn't give string.");
return;
}
NSString *baseURL = #"http://labs.valtyrorn.com/bin/leit.php?q=";
NSString *q = [pboard stringForType:NSPasteboardTypeString];
NSString * encoded = [q stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *query = [NSString stringWithFormat:#"%#%#", baseURL, encoded];
[webView setMainFrameURL:query];
NSLog(query);
}
and the service part of the plist looks like this:
<key>NSServices</key>
<array>
<dict>
<key>NSSendTypes</key>
<array>
<string>NSStringPboardType</string>
</array>
<key>NSMessage</key>
<string>serviceQuery</string>
<key>NSMenuItem</key>
<dict>
<key>default</key>
<string>Fáðu beygingarlýsingu</string>
</dict>
<key>NSPortName</key>
<string>BIN</string>
<key>NSRequiredContext</key>
<dict></dict>
</dict>
</array>
Does anyone know how to fix this?

File Tree Structure into NSDictionary

I'm trying to read a full File/Folder Structure (starting from a given Folder) into an NSDictionary (with a NSArrays,etc), like this :
Let's say starting folder is : /Users/some-user/some-path
We go in there and list all folders/subfolders/files
A/
file_a.txt
file_b.txt
subfolder/
file_c.txt
B/
etc...
What I want is to convert this file structure (probably using enumerators and NSFileManager) into an NSDictionary like :
<key>folder</key>
<string>A</string>
<key>values</key>
<array>
<dict>
<key>file</key>
<string>file_a.txt</string>
<key>url</key>
<string>/Users/some-user/some-path/A/file_a.txt</string>
</dict>
<dict>
<key>file</key>
<string>file_b.txt</string>
<key>url</key>
<string>/Users/some-user/some-path/A/file_b.txt</string>
</dict>
<dict>
<key>folder</key>
<string>subfolder</string>
<key>values</key>
<array>
...
</array>
</dict>
</array>
Any ideas?
Well this is the working result :
To check if a path is a Directory/Package/Bundle, etc :
- (BOOL)isDir:(NSString*)path
{
BOOL isDir;
if (([[NSFileManager defaultManager]
fileExistsAtPath:path isDirectory:&isDir] && isDir) ||
([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path]))
return YES;
else
return NO;
}
The actual function (using recursion) :
- (NSArray*)getContents:(NSString*)path {
NSError* err = nil;
NSArray* files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&err];
NSMutableArray* conts = [[NSMutableArray alloc] initWithObjects: nil];
for (NSString* c in files)
{
NSDictionary* d;
NSString* p = [d stringByAppendingPathComponent:d];
if (![self isDir:p])
{
d = [NSDictionary dictionaryWithObjectsAndKeys:
c,#"name",
p,#"url", nil];
}
else
{
d = [NSDictionary dictionaryWithObjectsAndKeys:
c,#"group",
p,#"entries", nil];
}
[conts addObject:d];
}
return conts;
}