[英]IOS push notifications between devices - GCDAsyncSocket
各位資深程序員,
我正在嘗試允許用戶向其他用戶發送推送通知(例如發送好友請求等)。
我的iOS應用程序的最終目標是,一旦用戶登錄到自己的帳戶(也就是加載了特定的視圖),我的iOS應用程序便會繼續監聽特定的主機名/端口URL。 我的堆棧是與MongoDB通信的Express服務器。
假設有一個{account_id}登錄的用戶,其帳戶信息的路徑為:“ http://72.89.157.153:3000/accounts/ {account_id}
我希望我的應用程序監聽發送到此URL的所有請求。 我正在使用GCDAsyncSocket庫來幫助解決該問題。 但是,當我出於測試目的連接到http://72.89.157.153:3000/時 ,沒有調用任何委托函數。 我見過很多人也遇到同樣的問題,但是我無法獲得解決方案。
碼:
套接字連接
#ifndef SocketConnection_h
#define SocketConnection_h
#import "GCDAsyncSocket.h" // for TCP
@import CocoaAsyncSocket;
@interface SocketConnection : NSObject <GCDAsyncSocketDelegate>
/* GCDAsyncSocket */
@property (strong, nonatomic) GCDAsyncSocket *socket;
// Methods
+(SocketConnection *)sharedConnection;
@end
#endif /* SocketConnection_h */
套接字連接
#import <Foundation/Foundation.h>
#import "SocketConnection.h"
@implementation SocketConnection
+(SocketConnection *)sharedConnection {
static dispatch_once_t once;
static SocketConnection *instance;
dispatch_once(&once, ^{
instance = [[SocketConnection alloc] init];
});
return instance;
}
-(id)init {
_socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *err = nil;
if (![_socket connectToHost:@"http://72.89.157.153" onPort:3000 error:&err]) {
printf("\nDid Not Return Okay: %s\n", [[err localizedDescription] UTF8String]);
} else {
printf("\nReturned Okay\n"); // This is printed
}
return self;
}
/* ASNYC DELEGATES */
/* I am expecting this method to be called when connectToHost: is called in init.. */
- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port {
printf("I'm connected! Host:%s\n", [host UTF8String]);
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag {
printf("I have written That was easy.\n");
}
- (void)socket:(GCDAsyncSocket *)sender didReadData:(NSData *)data withTag:(long)tag {
printf("I have read That was easy.\n");
dispatch_async(dispatch_get_main_queue(), ^{
@autoreleasepool {
[_socket readDataWithTimeout:-1 tag:1];
}
});
}
@end
這是ViewController中創建SocketConnection實例的地方。
-(void)viewDidAppear:(BOOL)animated {
/* Socket connector */
SocketConnection *s = [SocketConnection sharedConnection];
printf("port: %hu\n" ,s.socket.connectedPort); // prints 0 right now
}
如果這不是實現我的目標的最佳方法,請指出正確的方向(鏈接閱讀,其他框架,庫等)。如有任何問題,請告訴我。
感謝您的幫助。
好的,對於您的第一個目標(允許用戶向其他用戶發送推送通知,並假設您具有帶有express和mongodb的node.js服務器端),請嘗試執行以下操作:
首先在服務器端安裝apn和node-gcm。
npm i --save apn node-gcm
這兩個軟件包用於將推送通知發送到ios和android。
一旦安裝了這些軟件包,請在服務器端建立一條路由以發送通知。 可以使用以下方法完成此操作:
const express = require('express');
const path = require('path');
const gcm = require('node-gcm');
const apn = require('apn');
const apnProvider = new apn.Provider({
token: {
// YOU CAN FOUND THIS KEYS AND THE CERTIFICATE ON APPLE DEVELOPERS SITE
key: path.resolve(__dirname, 'PATH TO YOUR CERTIFICATE.P8'),
keyId: YOUR APN KEY ID,
teamId: YOUR APN TEAM ID,
},
production: false,
});
router.post('/sendNotification', (req, res) => {
const deviceToken = req.body.token;
const message = req.body.message;
const payload = req.body.payload;
const packages = req.body.package;
switch (packages) {
case 'com.foo.bar': {
const notification = new apn.Notification();
notification.topic = 'com.foo.bar';
notification.expiry = Math.floor(Date.now() / 1000) + 3600;
notification.badge = 1;
notification.sound = 'ping.aiff';
notification.alert = { message };
notification.payload = { payload };
apnProvider.send(notification, deviceToken).then((result) => {
return result === 200 ? res.sendStatus(200, result) : res.sendStatus(400);
});
break;
}
case 'com.yourteam.foo.bar': {
const androidMessage = new gcm.Message({
priority: 'high',
contentAvailable: true,
delayWhileIdle: false,
timeToLive: 10,
restrictedPackageName: 'com.yourteam.foo.bar',
dryRun: false,
data: {
title: 'foo',
icon: '@mipmap/logo',
notId: parseInt(Math.random() * new Date().getSeconds(), 10),
message,
},
});
const sender = new gcm.Sender(YOUR_KEY);
const registrationTokens = [deviceToken];
sender.send(androidMessage, { registrationTokens }, (err, response) => {
return err ? res.send(err) : res.send(response);
});
break;
}
default:
return res.sendStatus(400);
}
});
現在要發送推式通知,您需要像這樣進行POST:
iOS
目標C
#import <Foundation/Foundation.h>
NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded",
@"cache-control": @"no-cache"
NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"token=xxxxx" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&message=xxxxx" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&payload=xxxxx" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[@"&package=xxxxx" dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://72.89.157.153:3000/notifications/sendNotification"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"%@", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(@"%@", httpResponse);
}
}];
[dataTask resume];
迅速
import Foundation
let headers = [
"content-type": "application/x-www-form-urlencoded",
"cache-control": "no-cache"
]
let postData = NSMutableData(data: "token=xxxxx".data(using: String.Encoding.utf8)!)
postData.append("&message=xxxxx".data(using: String.Encoding.utf8)!)
postData.append("&payload=xxxxx".data(using: String.Encoding.utf8)!)
postData.append("&package=xxxxx".data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(url: NSURL(string: "http://72.89.157.153:3000/notifications/sendNotification")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
網路(AJAX)
var settings = {
"async": true,
"crossDomain": true,
"url": "http://72.89.157.153:3000/notifications/sendNotification",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"cache-control": "no-cache"
},
"data": {
"token": "xxxxx",
"message": "xxxxx",
"payload": "xxxxx",
"package": "xxxxx"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
爪哇
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "token=xxxxx&message=xxxxx&payload=xxxxx&package=xxxxx");
Request request = new Request.Builder()
.url("http://72.89.157.153:3000/notifications/sendNotification")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
現在,您可以向所有設備發送推送通知。
您的第二個目標可以在服務器端輕松實現,當請求發送到您的URL時,您可以執行POST發送推送通知,例如,如果有人想將您添加為朋友(讓我們說他們提出了請求)到http://72.89.157.153:3000/friends/ {account_id}),您可以向用戶發送通知,告訴他他有新的友誼請求。
重要的是,在mongodb上,您可以存儲軟件包和用戶令牌,因此您可以發送正確的通知。
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.