2016-09-24 11 views
8

में मैं आईओएस 10 पुश अधिसूचना में मीडिया जोड़ना चाहता हूं लेकिन छवियां पुश में काम नहीं कर रही हैं। उद्देश्य-सी में ऐसा कैसे करें?आईओएस 10 रिच मीडिया पुश अधिसूचना (मीडिया अटैचमेंट) उद्देश्य-सी

AppDelegate.h

#import <UIKit/UIKit.h> 
#import <CoreLocation/CoreLocation.h> 
#import <UserNotifications/UserNotifications.h> 

@interface AppDelegate : UIResponder <UIApplicationDelegate,CLLocationManagerDelegate,UNUserNotificationCenterDelegate> 

@property (strong, nonatomic) UIWindow *window; 
@end 

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
    if(SYSTEM_VERSION_LESS_THAN(@"10.0")) { 
     [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]]; 
     [[UIApplication sharedApplication] registerForRemoteNotifications]; 
    } else{ 
     UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; 
     center.delegate = self; 
     [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) 
     { 
      if(!error) { 
       [[UIApplication sharedApplication] registerForRemoteNotifications]; 
       // required to get the app to do anything at all about push notifications 
       NSLog(@"Push registration success."); 
      } else { 
       NSLog(@"Push registration FAILED"); 
       NSLog(@"ERROR: %@ - %@", error.localizedFailureReason, error.localizedDescription); 
       NSLog(@"SUGGESTIONS: %@ - %@", error.localizedRecoveryOptions, error.localizedRecoverySuggestion); 
      } 
     }]; 
    } 
} 

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 
    NSString * token = [NSString stringWithFormat:@"%@", deviceToken]; 
    //Format token as per need: 
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""]; 
    token = [token stringByReplacingOccurrencesOfString:@">" withString:@""]; 
    token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""]; 
    NSLog(@"Device Token is \n%@",token); 
} 

-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error 
{ 
    NSLog(@"Error:%@",error); 
} 

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { 
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) { 
     [self application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:^(UIBackgroundFetchResult result){}]; 
    } else { 
     /// previous stuffs for iOS 9 and below. I've shown an alert wth received data. 
    } 
} 

-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void(^)(UIBackgroundFetchResult))completionHandler { 
    // iOS 10 will handle notifications through other methods 

    if(NOTIFY_VISITORS_SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) 
    { 
     NSLog(@"iOS version >= 10. Let NotificationCenter handle this one."); 
     // set a member variable to tell the new delegate that this is background 
     return; 
    } 
    NSLog(@"HANDLE PUSH, didReceiveRemoteNotification: %@", userInfo); 
    // custom code to handle notification content 
    if([UIApplication sharedApplication].applicationState == UIApplicationStateInactive) 
    { 
     NSLog(@"INACTIVE"); 
     completionHandler(UIBackgroundFetchResultNewData); 
    } 
    else if([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) 
    { 
     NSLog(@"BACKGROUND"); 
     completionHandler(UIBackgroundFetchResultNewData); 
    } 
    else 
    { 
     NSLog(@"FOREGROUND"); 
     completionHandler(UIBackgroundFetchResultNewData); 
    } 
} 

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler { 
    NSLog(@"Handle push from foreground"); 
    // custom code to handle push while app is in the foreground 
    NSLog(@"%@", notification.request.content.userInfo); 
} 

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler { 
    NSLog(@"Handle push from background or closed"); 
    // if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background 
    NSLog(@"%@", response.notification.request.content.userInfo); 

तो मैं निम्नलिखित के रूप में एक नया लक्ष्य अधिसूचना सेवा विस्तार जोड़ दिया है: मेरे कोड इस प्रकार है:

NotificationService.h

#import <UserNotifications/UserNotifications.h> 
@interface NotificationService : UNNotificationServiceExtension 
@end 

NotificationService.m

#import "NotificationService.h" 

@interface NotificationService() 

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver); 
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent; 

@end 

@implementation NotificationService 

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler { 
    self.contentHandler = contentHandler; 
    self.bestAttemptContent = [request.content mutableCopy]; 

    // Modify the notification content here... 
    //self.bestAttemptContent.body = [NSString stringWithFormat:@"%@ [modified]", self.bestAttemptContent.body]; 

    // check for media attachment, example here uses custom payload keys mediaUrl and mediaType 
    NSDictionary *userInfo = request.content.userInfo; 
    if (userInfo == nil) { 
     [self contentComplete]; 
     return; 
    } 

    NSString *mediaUrl = userInfo[@"mediaUrl"]; 
    NSString *mediaType = userInfo[@"mediaType"]; 

    if (mediaUrl == nil || mediaType == nil) { 
     [self contentComplete]; 
     return; 
    } 

    // load the attachment 
    [self loadAttachmentForUrlString:mediaUrl 
          withType:mediaType 
        completionHandler:^(UNNotificationAttachment *attachment) { 
         if (attachment) { 
          self.bestAttemptContent.attachments = [NSArray arrayWithObject:attachment]; 
         } 
         [self contentComplete]; 
        }]; 

} 

- (void)serviceExtensionTimeWillExpire { 
    // Called just before the extension will be terminated by the system. 
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. 
    [self contentComplete]; 
} 

- (void)contentComplete { 
    self.contentHandler(self.bestAttemptContent); 
} 

- (NSString *)fileExtensionForMediaType:(NSString *)type { 
    NSString *ext = type; 

    if ([type isEqualToString:@"image"]) { 
     ext = @"jpg"; 
    } 

    if ([type isEqualToString:@"video"]) { 
     ext = @"mp4"; 
    } 

    if ([type isEqualToString:@"audio"]) { 
     ext = @"mp3"; 
    } 

    return [@"." stringByAppendingString:ext]; 
} 

- (void)loadAttachmentForUrlString:(NSString *)urlString withType:(NSString *)type completionHandler:(void(^)(UNNotificationAttachment *))completionHandler { 

    __block UNNotificationAttachment *attachment = nil; 
    NSURL *attachmentURL = [NSURL URLWithString:urlString]; 
    NSString *fileExt = [self fileExtensionForMediaType:type]; 

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 
    [[session downloadTaskWithURL:attachmentURL 
       completionHandler:^(NSURL *temporaryFileLocation, NSURLResponse *response, NSError *error) { 
        if (error != nil) { 
         NSLog(@"%@", error.localizedDescription); 
        } else { 
         NSFileManager *fileManager = [NSFileManager defaultManager]; 
         NSURL *localURL = [NSURL fileURLWithPath:[temporaryFileLocation.path stringByAppendingString:fileExt]]; 
         [fileManager moveItemAtURL:temporaryFileLocation toURL:localURL error:&error]; 

         NSError *attachmentError = nil; 
         attachment = [UNNotificationAttachment attachmentWithIdentifier:@"" URL:localURL options:nil error:&attachmentError]; 
         if (attachmentError) { 
         NSLog(@"%@", attachmentError.localizedDescription); 
         } 
        } 
        completionHandler(attachment); 
       }] resume]; 
} 
@end 

और मेरे अधिसूचना सेवा विस्तार Info.plist है: Notification Service Extension Info.plist

और मैं करने के लिए PHP स्क्रिप्ट का उपयोग कर रहा निम्नानुसार पुश अधिसूचना भेजें:

TestPush.php

<?php 

// Put your device token here (without spaces): 
    $deviceToken = 'my device tocken goes here'; 
// Put your private key's passphrase here: 
$passphrase = 'mypassphase'; 
// Put your alert message here: 
$message = 'Test iOS 10 Media Attachment Push'; 

//////////////////////////////////////////////////////////////////////////////// 

$ctx = stream_context_create(); 
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem'); 
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); 
stream_context_set_option($ctx, 'ssl', 'cafile', 'entrust_2048_ca.cer'); 

// Open a connection to the APNS server 
$fp = stream_socket_client(
    'ssl://gateway.sandbox.push.apple.com:2195', $err, 
    $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); 

if (!$fp) 
    exit("Failed to connect: $err $errstr" . PHP_EOL); 

echo 'Connected to APNS' . PHP_EOL; 

// Create the payload body 
$body['aps'] = array(
    'alert' => $message, 
    'sound' => 'default', 
    'mutable-content' => 1, 
    'category'=> "pusher" 
    ); 
$body['data'] = array(
    'mediaUrl' => "http://www.alphansotech.com/wp-content/uploads/2015/12/Push-notification-1.jpg", 
    'mediaType' => "jpg" 
); 
// Encode the payload as JSON 
$payload = json_encode($body); 

// Build the binary notification 
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; 

// Send it to the server 
$result = fwrite($fp, $msg, strlen($msg)); 

if (!$result) 
    echo 'Message not delivered' . PHP_EOL; 
else 
    echo 'Message successfully delivered' . PHP_EOL; 

// Close the connection to the server 
fclose($fp); 

छवियाँ और फ़ाइल साझा सर्वर पूआ पर होस्ट कर रहे हैं अपने लिंक भेज यह दिखाने के लिए होगा।

क्या कोई मेरी मदद कर सकता है।

+0

हैलो मैं इसे उद्देश्य-सी पर भी लागू करने की कोशिश कर रहा हूं लेकिन ऑनलाइन कोई संसाधन नहीं ढूंढ सकता ... क्या आप अपना कोड और/या आपके द्वारा उपयोग किए जाने वाले संसाधन के लिंक को साझा करने में सक्षम होंगे? धन्यवाद! – SJTriggs

+0

उपरोक्त कोड केवल ठीक काम कर रहा है ऑडियो और वीडियो उसमें काम नहीं कर रहा है। [इस प्रश्न] के पहले जवाब में केवल पेलोड प्रारूप को बदलने की आवश्यकता है (http://stackoverflow.com/questions/39673707/ios-10-rich-media-push-notification-media-attachment-in-objective-c ? noredirect = 1 # comment67813533_39673707) .और यदि आपको ऑडियो और वीडियो का समर्थन करने के लिए कोई समाधान मिलता है तो कृपया मुझे वह समाधान भी देखें। –

+0

मैंने उपरोक्त कोड और पेलोड लागू किया है लेकिन यह पूरी तरह से काम नहीं कर रहा है, मुझे लगता है कि इसमें info.plist के साथ कुछ करना है क्योंकि मैं आपके स्क्रीन शॉट में कुंजी नाम नहीं देख सकता। – SJTriggs

उत्तर

4

अपने कोड ठीक है, यह सिर्फ उम्मीद एक अलग पुश अधिसूचना डाटा प्रारूप: के साथ

// Create the payload body 
$body['aps'] = array(
    'alert' => $message, 
    'sound' => 'default', 
    'mutable-content' => 1, 
    'category'=> "pusher" 
    ); 
$body['data'] = array(
    'mediaUrl' => "http://www.alphansotech.com/wp-content/uploads/2015/12/Push-notification-1.jpg", 
    'mediaType' => "jpg" 
); 

:

इस हिस्से के बजाय ऐसे

$body = array(
    'aps' => array(
    'alert' => 'Rich notification', 
    'sound' => 'default', 
    'mutable-content' => 1 
), 
    'mediaUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/FloorGoban.JPG/1024px-FloorGoban.JPG', 
    'mediaType' => 'image' 
); 

कृपया ध्यान दें, उस छवि को चाहिए https://

+0

यह काम कर रहा है फोन, लेकिन मैं यूट्यूब वीडियो खेलने के लिए जब मैं एम्बेड कोड लिंक दे दिया है असमर्थ हूँ मैं अपने कोड है कि सभी छवि का समर्थन करना चाहिए अद्यतन करना चाहते, वीडियो और ऑडियो प्रारूप। –

+0

मैं पुश में वीडियो खेलना चाहता हूं लेकिन यह उपरोक्त कोड में समर्थन नहीं कर रहा है कि आप इसे कैसे उपरोक्त कोड से वीडियो चलाने में मदद कर सकते हैं। –

+0

@ आश्रफ क्या आप समृद्ध पुश अधिसूचनाओं के उपयोग और परियोजना निर्माण के बारे में जानने के लिए कोई नमूना डेमो लिंक प्रदान कर सकते हैं ?? पुश अधिसूचना में रिच मीडिया अटैचमेंट के डेमो को देखने के लिए – Ramakrishna

5

के माध्यम से सुलभ हो इसके लिए अतिरिक्त चेतावनी काम नहीं करने के लिएअधिसूचना सेवा Deployment Target मान है कि आपके परीक्षण डिवाइस द्वारा समर्थित नहीं है।

मेरे मामले में अधिसूचना सेवा खाका अपने 10.2 करने के लिए अपने Deployment Target निर्धारित किया था, जबकि मेरी परीक्षण उपकरण 10.1

है मुझे अपने एक्सटेंशन सेटअप कॉन्फ़िगर करते समय इसकी पहले से ही सब साथ काम के घंटे बर्बाद किया!

+0

इसे भी पकड़ा। –

संबंधित मुद्दे