Objective C — язык для гомофилов!

Вроде бы Яббл обещает новый языг программирования и откажется от Object C.

Как же так? Это же такой классный и забористый языг! Вот смотрите на что я целый день сегодня потратит, как же я теперь буду жить без такого красивого и полезного кода? 🙂


//------------------------------------------------------------------------------
// Posts generic OpenGraph to Facebook

+ (void)postOpenGraphAction: (NSString*) ogAction
                  forObject: (NSString*) ogObject
                    withUrl: (NSString*) ogObjectUrl
{
    
    NSMutableDictionary* params = [[NSMutableDictionary alloc]
        initWithObjectsAndKeys: ogObjectUrl, ogObject, nil];
    
    [FBRequestConnection
        startWithGraphPath  : ogAction
        parameters          : params
        HTTPMethod          : @"POST"
        completionHandler   :^
            (FBRequestConnection *connection, id result, NSError *error)
            {
                if (error) {
                    NSLog(@"Post using postOpenGraphAction() failed, error: %@", error);
                } else {
                    NSLog(@"Post using postOpenGraphAction() success, id: %@", [result objectForKey: @"id"]);
                }

#if DEBUG
                NSString* alertText = @"OpenGraph posted successfully.";
                if (error)
                    alertText = [NSString
                        stringWithFormat: @"OpenGraph error: domain = %@, code = %d",
                                 error.domain, error.code];

                // Show the result in an alert
                [[[UIAlertView alloc]
                    initWithTitle       : @"Result"
                    message             : alertText
                    delegate            : self
                    cancelButtonTitle   : @"OK!"
                    otherButtonTitles   : nil]
                show];
#endif
            }
     ];
}

//------------------------------------------------------------------------------
// Posts picture by fileName into existing Facebook album with given albumId
// Use @"me" as albumId to post directly onto user photos/timeline.
// Album must exit!  You need "user_photos" permission
// If don't know ID of album use postOpenGraphPicture with album name
+ (void)postOpenGraphPictureToExistingAlbum: (NSString*) fileName
                                       byId: (NSString*) albumId
                                withMessage: (NSString*) messageText
{
    UIImage* image;
    NSData* imageData;
    
    if (fileName && [fileName length] > 0)
    {
        // Add full path of file name if there is no slash
        NSString* fileNameFull = fileName;
        if ([fileNameFull rangeOfString: @"/"].location == NSNotFound)
        {
            NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString* documentsDirectory = [paths objectAtIndex: 0];
            fileNameFull = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: @"%@", fileName]];
        };
        
        // Load imageData depending on file extension
        image = [UIImage imageWithContentsOfFile: fileNameFull];
        if ([fileNameFull rangeOfString: @"/"].location != NSNotFound)
            imageData = UIImagePNGRepresentation(image);
        else
            imageData = UIImageJPEGRepresentation(image, 1.0);
    } else
    {
        // Todo: Change default picture resource here
        image = [UIImage imageNamed: @"screenshot.png"];
        imageData = UIImagePNGRepresentation(image);
    }

    NSMutableDictionary* paramsPicture = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
      messageText   , @"message",
      imageData     , @"picture",
      nil];

    NSString* graphPath = [NSString stringWithFormat:@"%@/photos", albumId];

    [FBRequestConnection
        startWithGraphPath  : graphPath
        parameters          : paramsPicture
        HTTPMethod          : @"POST"
        completionHandler   : ^
            (FBRequestConnection *connection, id result, NSError *error)
            {
#if DEBUG
                NSString* alertText;
                if (!error)
                    alertText= @"Picture posted successfully.";
                else
                    alertText = [NSString stringWithFormat: @"Cannot post '%@' picture, error: %@", fileName, error];

                // Show the result in an alert
                [[[UIAlertView alloc]
                initWithTitle       : @"Result"
                message             : alertText
                delegate            : self
                cancelButtonTitle   : @"OK!"
                otherButtonTitles   : nil]
                show];
#endif
     
            }
    ];
} // postOpenGraphPictureToExistingAlbum


//------------------------------------------------------------------------------
// Posts picture stored in fileName to Facebook
// You may specify some album by albumName parameter.
// If album doesn't exits, function will try to create it.
// You need "user_photos" permission to get list of albums!
+ (void)postOpenGraphPicture: (NSString*) fileName
                 withMessage: (NSString*) messageText
                     toAlbum: (NSString*) albumName
             withDescription: (NSString*) albumDescription
{
    
    // If no Album specified, post picture as "me/photos" onto timeline
    if ((!albumName) || ([albumName length] < 1))
    {
        [self postOpenGraphPictureToExistingAlbum: fileName
                                             byId: @"me"
                                      withMessage: messageText];
        return;
    }
    
    
    // Get album or create a new one, then post picture
    // You need "user_photos" permission to get list of albums!
    [FBRequestConnection
            startWithGraphPath  : @"me/albums"
            completionHandler   : ^
        (FBRequestConnection *connection, id result, NSError *error)
        {
            bool        albumFound  = false;             // true if Album found or created
            NSString*   albumId     = [NSString alloc];  // Facebook Album ID will be here

            // Verify does Album exist
            NSDictionary* dictionary = (NSDictionary*) result;
            NSArray* albums = [dictionary objectForKey : @"data"];
            for (NSDictionary* album in albums)
            {
                NSString* name = album[@"name"];
                bool canUpload = album[@"can_upload"];
                if (canUpload && [name isEqualToString: albumName] )
                {
                    albumFound  = true;
                    albumId = album[@"id"];
                    break; // We can upload to this album.
                }
            }

            // There is no writable album for given criteria, try to create new one
            if (!albumFound)
            {
                NSMutableDictionary* paramsAlbum = [[NSMutableDictionary alloc] initWithObjectsAndKeys :
                    albumName           , @"name",
                    albumDescription    , @"description",
                  nil];

                [FBRequestConnection
                    startWithGraphPath  : @"me/albums"
                    parameters          : paramsAlbum
                    HTTPMethod          : @"POST"
                    completionHandler   : ^
                        (FBRequestConnection *connection, id result, NSError *error)
                        {
                            if (!error)
                            {
                                NSLog(@"Facebook album '%@' succesefully creaded", albumName);
                                
                                // Post picture into new album
                                [self postOpenGraphPictureToExistingAlbum: fileName
                                                                     byId: result[@"id"]
                                                              withMessage: messageText];
                            } else
                                NSLog(@"Cannot create Facebook album '%@', error: %@", albumName, error);
                        }
                ];
                return; // Stop any other tasks
            }

            // Post picture if album exists
            [self postOpenGraphPictureToExistingAlbum: fileName
                                                 byId: albumId
                                          withMessage: messageText];
        }
     ]; // [FBRequestConnection startWithGraphPath: @"me/albums" completionHandler: ^

} // postOpenGraphPicture


//------------------------------------------------------------------------------
// Makes screenshot of current GUI and saves it into file with given fileName.
// If fileName contains only short name the file is saved into Document dir.

- (void)screenshotToFile: (NSString*) fileName
{
    //Todo: Modify theView to a proper View
    UIView* theView = self.view;
    
    // Get context depending on resolution (retina or not)
    if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
        UIGraphicsBeginImageContextWithOptions(theView.window.bounds.size, NO, [UIScreen mainScreen].scale);
    else
        UIGraphicsBeginImageContext(theView.window.bounds.size);
    
    // Get image
    UIGraphicsBeginImageContext(theView.window.bounds.size);
    [theView.window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // Get image data in format specified by extension of fileName
    NSData* data;
    if ([fileName rangeOfString: @".png"].location != NSNotFound)
        data = UIImagePNGRepresentation(image);
    else if ([fileName rangeOfString: @".jpg"].location != NSNotFound)
        data = UIImageJPEGRepresentation(image, 1.0);
    else
        data = UIImageJPEGRepresentation(image, 0.5); // Low-res Jpeg by default
    
    // Add full path of file name if there is no slash
    NSString* fileNameFull = fileName;
    if ([fileNameFull rangeOfString: @"/"].location == NSNotFound)
    {
        NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString* documentsDirectory = [paths objectAtIndex: 0];
        fileNameFull = [documentsDirectory stringByAppendingPathComponent:
            [NSString stringWithFormat: @"%@", fileName]];
    };
    
    // Write to the file
    [data writeToFile: fileNameFull atomically: YES];
}


//------------------------------------------------------------------------------
// Button event

- (IBAction)buttonScreenshotTouchDown:(UIButton *)sender {
    
    NSString* fileName = @"screenshot-or-other-file-name.jpg";
    
    // Make screenshot
    [self screenshotToFile: fileName];
    
    
    // Prepare date and time stamp
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString* dateStr = [formatter stringFromDate: [NSDate date]];
        [formatter setDateFormat:@"HH:mm"];
    NSString* timeStr = [formatter stringFromDate: [NSDate date]];
    
    // Add current date stamps into message
    NSString* message = [NSString stringWithFormat:
                         @"Mega screenshot created on %@ at %@", dateStr, timeStr];
    
    // Post screenshot into some album
    [megaViewController postOpenGraphPicture: fileName
                                 withMessage: message
                                     toAlbum: @"Mega Screenshots"
                             withDescription: @"Test album for different screenshots"
    ];
    
    // Post screenshot onto timeline
    [megaViewController postOpenGraphPictureToExistingAlbum: fileName
                                                       byId: @"me"
                                                withMessage: message
    ];
    
    // Post simple OpenGraph action
    [megaViewController
        postOpenGraphAction : @"/me/karpolan-test:complete"
        forObject           : @"quest"
        withUrl             : @"http://karpolan.com/social/karpolan-test/quest.html"
    ];
    
}

Блин, не могли в Яббл убить ОбжЦе полгода назад, я бы даже не тратил нервы на изучение этой параши!

P.S. Код действительно полезный, надеюсь кому-то пригодится. Потому что iOS + Facebook SDK это Аддд в квадрате!

Objective C — язык для гомофилов!: 4 комментария

Добавить комментарий

Заполните поля или щелкните по значку, чтобы оставить свой комментарий:

Логотип WordPress.com

Для комментария используется ваша учётная запись WordPress.com. Выход /  Изменить )

Google photo

Для комментария используется ваша учётная запись Google. Выход /  Изменить )

Фотография Twitter

Для комментария используется ваша учётная запись Twitter. Выход /  Изменить )

Фотография Facebook

Для комментария используется ваша учётная запись Facebook. Выход /  Изменить )

Connecting to %s