2016-10-10 95 views
3

首先我是用Swift开发的,我有Objective C背景,但我主要是Android开发人员。iOS 10带图片的远程通知

其实我正在Swift 3和Xcode 8中开发一个应用程序。我需要在这个应用程序中添加Apple的新推送通知系统。

我已经能够添加一个本地丰富的通知示例与图片,视频和GIF。但是我需要在典型的互联网服务器上显示远程通知和图片。

要启动本地通知我用这个代码:

@IBAction func launchPicNotification(sender: UIButton) { 
    let content = UNMutableNotificationContent() 
    content.title = "Title" 
    content.body = "Body" 
    content.sound = UNNotificationSound.default() 

    let url = Bundle.main.url(forResource:"foto", withExtension: "jpg") 

    let attachment = try? UNNotificationAttachment(identifier: "Notification", 
                url: url!, 
                options: [:]) 

    if let attachment = attachment { 
     print("Yes") 
     content.attachments.append(attachment) 
    }else{ 
     print("No") 
    } 

    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 10.0, repeats: false) 
    let request = UNNotificationRequest(identifier:"identificador", content: content, trigger: trigger) 

    UNUserNotificationCenter.current().add(request){(error) in 

     if (error != nil){ 

      //handle here 

     } 

    } 
} 

我需要加载远程JPG文件作为附加的图像。有人知道我如何加载远程文件,而不是加载本地图片?

谢谢

+0

'let url = URL(string:“https://.....jpg”)''?或者必须将url指向本地文件。如果是这样的话,你需要先下载文件 – jbe

+0

我已经试过了,也许我需要先下载它,如你告诉我的。你能推荐我一个很好的教程来下载Swift 3上的照片吗?谢谢。 – gabicuesta

+0

@ gabicuesta你需要首先下载文件,而不是在通知中显示图像。 –

回答

1

我为UIImage添加了一个扩展来处理这个。一旦你从下载的数据创建了UIImage,你可以调用这个函数来创建一个本地URL。

extension UIImage { 

func createLocalURL() -> URL? { 

    guard let data = UIImagePNGRepresentation(self) else { 
     print("Coule not get UIImagePNGRepresentation Data for photo") 
     return nil 
    } 

    let localUrl = self.getDocumentsDirectory().appendingPathComponent("copy.png") 

    do { 
     try data.write(to: localUrl) 
    } catch let error { 
     print("Failed to write to URL") 
     print(error) 
    } 
    return localUrl 
} 

}