获取推送通知令牌 - iOS 10,Swift 3

时间:2016-09-19 04:02:42

标签: push-notification notifications swift3 ios10

如何从iOS 10中的新xCode 8,Swift 3获取设备令牌?

这里是注册通知的代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        DispatchQueue.main.async {
            let settings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(settings)
        }
        return true
    }

func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
        if notificationSettings.types != UIUserNotificationType() {
            application.registerForRemoteNotifications()
        }
    }

此处获取令牌,但我收到错误"无法调用类型' UnsafePointer'使用类型'(UnsafeRawPointer)的参数列表'":

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let chars = UnsafePointer<CChar>((deviceToken as NSData).bytes)
        var token = ""

        for i in 0..<deviceToken.count {
            token += String(format: "%02.2hhx", arguments: [chars[i]])
        }

        print("Registration succeeded!")
        print("Token: ", token)
    }

任何人都可以帮忙解决它吗?

由于

11 个答案:

答案 0 :(得分:34)

此方法可以解决iOS 10及更高版本中的问题:

<div class="row">
<div class="col-md-4 col-sm-4 col-xs-6 text-center">

    <div class="product_card">
        <a href="/buy/pork" title="Amazing porks" style="background-image: url('http://lorempixel.com/output/animals-q-c-640-480-6.jpg');"></a>
        <div data-target="#loginSignUpModal" data-toggle="modal" onclick="return false;">
            <i class="fa fa-star-o" aria-hidden="true"></i> Shortlist
        </div>

        <a class="caption" href="/buy/pork">
            <h3>Porks</h3>
            <span class="price">$380.00</span>
        </a></div>
<div class="product_card">
        <a href="/buy/rhinoceros" title="Rhinoceros from Africa" style="background-image: url('http://lorempixel.com/output/animals-q-c-600-400-1.jpg');"></a>
        <div data-target="#loginSignUpModal" data-toggle="modal" onclick="return false;">
            <i class="fa fa-star-o" aria-hidden="true"></i> Shortlist
        </div>

        <a class="caption" href="/buy/rhinoceros">
            <h3>Rhinoceros</h3>
            <span class="price">$8 000.00</span>
        </a></div>
<div class="product_card">
        <a href="/buy/dog" title="Cuttie dog" style="background-image: url('http://lorempixel.com/output/animals-q-c-800-800-8.jpg');"></a>
        <div data-target="#loginSignUpModal" data-toggle="modal" onclick="return false;">
            <i class="fa fa-star-o" aria-hidden="true"></i> Shortlist
        </div>

        <a class="caption" href="/buy/dog">
            <h3>Dogs</h3>
            <span class="price">$380.00</span>
        </a></div>
</div>
</div>

答案 1 :(得分:11)

var pushToken = String(format: "%@", deviceToken as CVarArg)
pushToken = pushToken.trimmingCharacters(in: CharacterSet(charactersIn: "<>"))
pushToken = pushToken.replacingOccurrences(of: " ", with: "")

答案 2 :(得分:5)

Swift 3示例取自raywenderlich.com

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){
    let tokenParts = deviceToken.map { data -> String in
        return String(format: "%02.2hhx", data)
    }  
    let token = tokenParts.joined()
    print(token)
}

答案 3 :(得分:3)

面对同样的问题,这是唯一帮助我的事情:

private String getToken()
        {           
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(mlib.IdentityServiceURL);
            request.ContentType = "application/json";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream resStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(resStream);
            String json = reader.ReadToEnd();
            //Dictionary<String, Object> dict = JavaScriptSerializer.DeserializeObject(reader.ReadToEnd);
            Dictionary<String, String> dict = JsonConvert.DeserializeObject<Dictionary<String, String>>(json);
            return dict["access_token"];
        }

答案 4 :(得分:1)

以下snnipet正在与Eric Aya解决方案合作:

let token = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})

感谢您的帮助:)

答案 5 :(得分:1)

用于获取推送通知令牌的工作代码-iOS 11或更高版本,Swift 4

请求用户权限

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    let notificationTypes: UIUserNotificationType = [UIUserNotificationType.alert,UIUserNotificationType.badge, UIUserNotificationType.sound]
    let pushNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil)

    application.registerUserNotificationSettings(pushNotificationSettings)
    application.registerForRemoteNotifications()

    return true        
}

获取设备令牌

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    print(token) 
}

如果发生错误

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {

    print("i am not available in simulator \(error)")
}

答案 6 :(得分:1)

一行:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let apnsDeviceToken = deviceToken.map {String(format: "%02.2hhx", $0)}.joined()
}

From this tutorial.

答案 7 :(得分:0)

它可以工作:

let chars = UnsafePointer<CChar>((deviceToken as NSData).bytes.assumingMemoryBound(to:CChar.self))

谢谢!

答案 8 :(得分:0)

快速5

 if #available(iOS 10.0, *) {
        let center = UNUserNotificationCenter.current()
        center.delegate = self;
        center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
            DispatchQueue.main.async(execute: {
                UIApplication.shared.registerForRemoteNotifications()
            })
        }
    } else {
        let setting = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(setting)
        UIApplication.shared.registerForRemoteNotifications()
    }

然后使用“ @chirag shah”请求获取通知代码。

答案 9 :(得分:0)

Mixpanel库中的代码

    let tokenChars = (deviceToken as NSData).bytes.assumingMemoryBound(to: CChar.self)
    var tokenString = ""
    for i in 0..<deviceToken.count {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

答案 10 :(得分:0)

由于您可能在不同的方法(如 firebase、web 参与、分支等)中需要此令牌,因此您可以使用自定义类从包含 datastring 的数据中初始化 APNS

public class APNS {
    public init(deviceToken data: Data) {
        self.data = data
        self.string = data.map { data in String(format: "%02.2hhx", data) } .joined()
    }

    public let data: Data
    public let string: String
}

然后你可以在任何你需要的地方使用它:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let token = APNS(deviceToken: deviceToken)
    print(token.string)
}