Skip to content

Commit

Permalink
And part 4
Browse files Browse the repository at this point in the history
  • Loading branch information
paul999 committed Jul 27, 2014
1 parent 3ab2cad commit 53709e4
Show file tree
Hide file tree
Showing 9 changed files with 262 additions and 12 deletions.
Binary file not shown.
Expand Up @@ -10,11 +10,11 @@
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "Symfony iOS Oauth Demo/Demo+Create.m"
timestampString = "425060204.708221"
timestampString = "428167633.043695"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "38"
endingLineNumber = "38"
startingLineNumber = "116"
endingLineNumber = "116"
landmarkName = "+createDemo:desc:serverId:inManagedObjectContext:"
landmarkType = "5">
</BreakpointContent>
Expand Down Expand Up @@ -67,5 +67,53 @@
landmarkType = "5">
</BreakpointContent>
</BreakpointProxy>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
shouldBeEnabled = "No"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "Symfony iOS Oauth Demo/Demo+Create.m"
timestampString = "428167248.553124"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "16"
endingLineNumber = "16"
landmarkName = "+getDataFromClient:inManagedObjectContent:refresh:completionHandler:"
landmarkType = "5">
</BreakpointContent>
</BreakpointProxy>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
shouldBeEnabled = "No"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "Symfony iOS Oauth Demo/Demo+Create.m"
timestampString = "428167633.043695"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "148"
endingLineNumber = "148"
landmarkName = "+deleteDemo:inManagedObjectContext:"
landmarkType = "5">
</BreakpointContent>
</BreakpointProxy>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
shouldBeEnabled = "No"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "Symfony iOS Oauth Demo/Demo+Create.m"
timestampString = "428167633.043695"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "56"
endingLineNumber = "56"
landmarkName = "+getDataFromClient:inManagedObjectContent:refresh:completionHandler:"
landmarkType = "5">
</BreakpointContent>
</BreakpointProxy>
</Breakpoints>
</Bucket>
3 changes: 2 additions & 1 deletion Symfony iOS Oauth Demo/Symfony iOS Oauth Demo/AppDelegate.h
Expand Up @@ -7,11 +7,12 @@
//

#import <UIKit/UIKit.h>
#import <NXOAuth2.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (nonatomic, strong) NXOAuth2Account *account;

@end

23 changes: 23 additions & 0 deletions Symfony iOS Oauth Demo/Symfony iOS Oauth Demo/AppDelegate.m
Expand Up @@ -9,6 +9,7 @@
#import "AppDelegate.h"
#import "AppDelegate+radio.h"
#import "DatabaseRadio.h"
#import "Demo+Create.h"

#import "NXOauth2.h"

Expand Down Expand Up @@ -53,9 +54,31 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(

self.DatabaseContext = [self createMainQueueManagedObjectContext];

[application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];


return YES;
}

-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
NSDate *fetchStart = [NSDate date];
NSLog(@"Background fetch");

if (!self.account || !self.DatabaseContext)
{
completionHandler(UIBackgroundFetchResultFailed);
}

[Demo getDataFromClient:self.account inManagedObjectContent:self.DatabaseContext refresh:nil completionHandler:^(UIBackgroundFetchResult result) {
completionHandler(result);

NSDate *fetchEnd = [NSDate date];
NSTimeInterval timeElapsed = [fetchEnd timeIntervalSinceDate:fetchStart];
NSLog(@"Background Fetch Duration: %f seconds", timeElapsed);
}];

}

- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
Expand Down
Expand Up @@ -46,6 +46,9 @@
</connections>
</barButtonItem>
</navigationItem>
<refreshControl key="refreshControl" opaque="NO" multipleTouchEnabled="YES" contentMode="center" enabled="NO" contentHorizontalAlignment="center" contentVerticalAlignment="center" id="GFX-sd-lkH">
<autoresizingMask key="autoresizingMask"/>
</refreshControl>
<connections>
<outlet property="addButton" destination="Lch-7H-jVV" id="A6G-vb-PZA"/>
</connections>
Expand Down Expand Up @@ -128,6 +131,7 @@
<connections>
<outlet property="demodesc" destination="gd7-a0-zwb" id="D5X-dW-Pth"/>
<outlet property="demotitle" destination="fj1-Nb-rfQ" id="Ujz-fs-ty3"/>
<outlet property="save" destination="gE8-pv-LAb" id="YF5-XS-BDs"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="njh-Ck-wgy" userLabel="First Responder" sceneMemberID="firstResponder"/>
Expand Down
Expand Up @@ -9,10 +9,12 @@
#import "CreateDemoViewController.h"
#import "Demo+Create.h"
#import <QuartzCore/QuartzCore.h>
#import <NXOAuth2.h>

@interface CreateDemoViewController ()
@interface CreateDemoViewController () <NXOAuth2ConnectionDelegate>
@property (weak, nonatomic) IBOutlet UITextField *demotitle;
@property (weak, nonatomic) IBOutlet UITextField *demodesc;
@property (weak, nonatomic) IBOutlet UIButton *save;

@end

Expand All @@ -30,7 +32,7 @@ - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibB
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.save.enabled = true;
}

- (void)didReceiveMemoryWarning
Expand All @@ -53,7 +55,6 @@ - (IBAction)createDemo:(id)sender {

NSString *title = self.demotitle.text;
NSString *desc = self.demodesc.text;
NSNumber *serverId = [NSNumber numberWithInt:arc4random()];

if ([title length] == 0 || [desc length] == 0)
{
Expand Down Expand Up @@ -83,11 +84,8 @@ - (IBAction)createDemo:(id)sender {
}
else
{
[Demo createDemo:title desc:desc serverId:serverId inManagedObjectContext:self.managedObjectContext];

NSLog(@"Created demo with serverId %@", serverId);

[self.navigationController popViewControllerAnimated:YES];
self.save.enabled = FALSE;
[self createDemoOnServer:title desc:desc];
}
}

Expand All @@ -97,6 +95,70 @@ - (void)setManagedObjectContext:(NSManagedObjectContext *)managedObjectContext
NSLog(@"Got a managed context");
}

- (void)createDemoOnServer:(NSString *)title
desc:(NSString *)desc
{
NSMutableDictionary *dt = [[NSMutableDictionary alloc]init];
[dt setValue:title forKey:@"title"];
[dt setValue:desc forKey:@"description"];

NSData *jsonData;

if ([NSJSONSerialization isValidJSONObject:dt]) {

NSError *error;
jsonData = [NSJSONSerialization dataWithJSONObject:dt options:NSJSONWritingPrettyPrinted error:&error];

if (error != nil)
{
NSLog(@"Error creating JSON data: %@", error);
return;
}
}
else
{
return;
}

NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@", jsonString); // To verify the jsonString.


NXOAuth2Request *theRequest = [[NXOAuth2Request alloc] initWithResource:[NSURL URLWithString:@"http://api.ip-6.nl/demos"]
method:@"POST"
parameters:nil];
theRequest.account = self.account;

NSMutableURLRequest *sigendRequest = [[theRequest signedURLRequest] mutableCopy];

[sigendRequest setHTTPMethod:@"POST"];
[sigendRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[sigendRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[sigendRequest setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];
[sigendRequest setHTTPBody:jsonData];


NXOAuth2Connection *connection = [[NXOAuth2Connection alloc] initWithRequest:sigendRequest
requestParameters:nil
oauthClient:self.account.oauthClient
sendingProgressHandler:nil
responseHandler:^(NSURLResponse *response, NSData *responseData, NSError *error){
NSLog(@"Done creating :) %@", error);

[Demo getDataFromClient:self.account inManagedObjectContent:self.managedObjectContext refresh: nil completionHandler:NULL];
self.save.enabled = true;

if (error)
{
// Might do something here?
NSLog(@"ERR");
}

[self.navigationController popViewControllerAnimated:YES];
}];
connection.delegate = self;
}

/*
#pragma mark - Navigation
Expand Down
9 changes: 9 additions & 0 deletions Symfony iOS Oauth Demo/Symfony iOS Oauth Demo/Demo+Create.h
Expand Up @@ -8,9 +8,18 @@

#import <Foundation/Foundation.h>
#import "demo.h"
#import <UIKit/UIKit.h>
#import <NXOAuth2.h>


@interface Demo (Create)

+ (void)getDataFromClient:(NXOAuth2Account *)account
inManagedObjectContent:(NSManagedObjectContext *)context
refresh:(UIRefreshControl *)refresh
completionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;


+ (Demo *)createDemo:(NSString *)title
desc:(NSString *)desc
serverId:(NSNumber *)serverId
Expand Down
78 changes: 78 additions & 0 deletions Symfony iOS Oauth Demo/Symfony iOS Oauth Demo/Demo+Create.m
Expand Up @@ -7,9 +7,85 @@
//

#import "Demo+Create.h"
#import <NXOAuth2.h>

@implementation Demo (Create)

+ (void)getDataFromClient:(NXOAuth2Account *)account
inManagedObjectContent:(NSManagedObjectContext *)context
refresh:(UIRefreshControl *)refresh
completionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
[NXOAuth2Request performMethod:@"GET"
onResource:[NSURL URLWithString:@"http://api.ip-6.nl/demos"]
usingParameters:nil
withAccount:account
sendProgressHandler:^(unsigned long long bytesSend, unsigned long long bytesTotal) { // e.g., update a progress indicator
NSLog(@"Send %llu total %llu", bytesSend, bytesTotal);
}
responseHandler:^(NSURLResponse *response, NSData *responseData, NSError *error){
if (error)
{
if (completionHandler)
{
completionHandler(UIBackgroundFetchResultFailed);
}
return;
}

NSError* err;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&err];

NSArray* dataArray = [json objectForKey:@"demos"];

NSMutableArray* avail = [[NSMutableArray alloc] init];

for (NSDictionary *row in dataArray)
{
NSString *title = [row objectForKey:@"title"];
NSString *desc = [row objectForKey:@"description"];


NSNumber *server = [NSNumber numberWithLong:
[[row objectForKey:@"id"] integerValue]];

[avail addObject:server];
[self createDemo:title desc:desc serverId:server inManagedObjectContext:context];
}


// Delete old crap
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Demo"];

NSError *erro;
NSArray *matches = [context executeFetchRequest:request error:&erro];

if ([matches count])
{
for (Demo *dm in matches)
{
if (![avail containsObject:dm.serverId])
{
NSLog(@"Deleting %@", dm.serverId);
[context deleteObject:dm];
}
}
}
if (refresh)
{
[refresh endRefreshing];
}

if (completionHandler)
{
completionHandler(UIBackgroundFetchResultNewData);
}
}];
}

+ (Demo *)findDemo:(NSNumber *)serverId
inManagedObjectContext:(NSManagedObjectContext *)context
{
Expand All @@ -34,6 +110,8 @@ + (Demo *)createDemo:(NSString *)title
serverId:(NSNumber *)serverId
inManagedObjectContext:(NSManagedObjectContext *)context
{
NSLog(@"Creating a demo with title %@, desc %@ and server %@", title, desc, serverId);

Demo *demo = nil;
if ([title length] && [desc length])
{
Expand Down

0 comments on commit 53709e4

Please sign in to comment.