Apple Tidings Format Api Inwards Swift: Exceed Channel, Department In Addition To Article Information (Swift 4)


You tin role the online tool to exercise your ain Apple News posts through iCloud.com, no problem. You tin also expect to Apple's python scripts equally a way to upload, download too delete articles. If it's a Swift equivalent you lot want, therefore you'll demand to curlicue your own. And that's what I start to exercise hither having covered a yoke of side notes first.

Side notes most Python

To role the Python scripts I needed to role easy_install to install requests on macOS.

Side notes on News Preview

To role the News Preview app, too start exploring the Apple News Format, you lot demand to lead keep Java 8 installed, Xcode too Xcode control occupation tools, too a channel id (although Apple does furnish a preview channel id inwards the readme file if you're non notwithstanding signed upwards to Apple News equally a content provider).

Once you lot lead keep everything installed select grip of the example articles and start learning.

Python: GET Channel Data

This is the Python code that Apple provides inwards its documentation for returning channel data:
#!/usr/bin/python  import requests import base64 from hashlib import sha256 import hmac from datetime import datetime channel_id = '[YOUR CHANNEL ID]' api_key_id = '[YOUR CHANNEL KEY]' api_key_secret = '[YOUR SECRET KEY]' url = 'https://news-api.apple.com/channels/%s' % channel_id appointment = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") canonical_request = 'GET' + url + str(date) primal = base64.b64decode(api_key_secret) hashed = hmac.new(key, canonical_request, sha256) signature = hashed.digest().encode("base64").rstrip('\n') ascendence = 'HHMAC; key=%s; signature=%s; date=%s' % (api_key_id, str(signature), date) headers = {'Authorization': authorization} reply = requests.get(url, headers=headers) impress response.text

Swift 4: GET Channel Data

And hither is a translation into Swift 4.

One of the starting fourth dimension things nosotros are going to demand to generate is the UTC fourth dimension string, therefore let's write a method for that:
 func utcTime() -> String {     if #available(OSX 10.12, *) {         allow formatter = ISO8601DateFormatter()         // GMT is default fourth dimension zone         render formatter.string(from: Date())     } else {         allow dateFormatter = DateFormatter()         //The Z at the cease of your string represents Zulu which is UTC;         allow timeZone = TimeZone(secondsFromGMT: 0)         dateFormatter.timeZone = timeZone         dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"         allow fourth dimension = dateFormatter.string(from: Date())         render fourth dimension     } } 
For macOS 10.12 (and iOS 10.0) forwards create a bridging header and import CommonCrypto, the methods for this tin therefore hold out written equally String extensions.
extension String {     // run across http://stackoverflow.com/a/24411522/1694526     func base64ToByteArray() -> [UInt8]? {         if allow information = Data(base64Encoded: self, options: []) {             render [UInt8](data)         }         render nothing // Invalid input     }          func createAppleSignature(key:String) -> String? {         if allow keyData = key.base64ToByteArray(),             allow paramData = self.data(using: String.Encoding.utf8),             allow hash = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH)) {             CCHmac(UInt32(kCCHmacAlgSHA256), keyData, keyData.count, [UInt8](paramData), paramData.count, hash.mutableBytes)             render hash.base64EncodedString(options: [])         }         render nothing     } } 
Now the additional bits too pieces are out the way we're laid to brand the asking to Apple News. And hither it all is packaged upwards inwards a method:

func channelData(channelID:String, apiKeyID: String, apiKeySecret:String) {     allow url = "https://news-api.apple.com/channels/\(channelID)"     allow appointment = utcTime()     allow canonical_request = "GET\(url)\(date)"              // don't worry most the primal too hashed lines of Python code here, nosotros embrace all that inwards the createAppleSignature code     if allow signature = canonical_request.createAppleSignature(key: apiKeySecret),         allow nsURL = URL(string: url) {         allow ascendence = "HHMAC; key=\(apiKeyID); signature=\(signature); date=\(date)"         allow headers = ["Authorization": authorization]                      // straight off brand NSURLSession GET asking         allow session = URLSession(configuration: URLSessionConfiguration.ephemeral)         var asking = URLRequest(url: nsURL)         request.allHTTPHeaderFields = headers         request.httpMethod = "GET"         allow dataTask = session.dataTask(with: request, completionHandler: {(data, response, error) inwards             if (error != nil) {                 print("error")             }             if allow reply = reply as? HTTPURLResponse {                 print(response.statusCode)                 print(response.allHeaderFields)             }             if allow information = information {                 print(String(data: data, encoding: String.Encoding.utf8) ?? "Fail")             }         })         dataTask.resume()     }          } 
Now assuming you lot lead keep everything set upwards amongst Apple to brand role of Apple News Format too their API, too lead keep an ID, Key too Secret, you lot should straight off hold out able to write the code to brand all this operate at the impact of a button. Something like:
@IBAction func channelDataReceive(_ sender: Any) {     allow channelID = ""     allow keyID = ""     allow cloak-and-dagger = ""      channelData(channelID: channelID, apiKeyID: keyID, apiKeySecret: secret) } 
which in i trial you've inserted your ID, Key too Secret volition operate in i trial you've hooked the method upwards to a push clit provided you lot accept i add-on step, which is to opened upwards up the app's permissions for communication amongst a server. If you lot are writing a macOS app, this tin hold out done inwards the app's Capabilities past times checking incoming too outgoing connections. (If you're writing for iOS, run across Appendix to this post on App Transport Security.)

The output you'll have dorsum is a JSON dictionary. This is a expert start because making requests too receiving/sending information are the Blue Planet of what needs to hold out done amongst Apple News.

Extending to shout upwards Section too Article Data

Not entirely tin you lot shout upwards the nitty-gritty channel information inwards this way but you lot tin also shout upwards department too article information amongst a slight modification past times starting fourth dimension creating a ChannelInfo enum:
enum ChannelInfo {     instance Data, Section, Article }
too therefore requiring our channelData: to accept a type:
func channelData(type:ChannelInfo, channelID:String, apiKeyID: String, apiKeySecret:String) {     allow url = type == .Data ? "https://news-api.apple.com/channels/\(channelID)" : type == .Article ? "https://news-api.apple.com/channels/\(channelID)/articles" : "https://news-api.apple.com/channels/\(channelID)/sections"     allow appointment = utcTime()     allow canonical_request = "GET\(url)\(date)"              // don't worry most the primal too hashed lines of Python code here, nosotros embrace all that inwards the createAppleSignature code     if allow signature = canonical_request.createAppleSignature(key: apiKeySecret),         allow nsURL = URL(string: url) {         allow ascendence = "HHMAC; key=\(apiKeyID); signature=\(signature); date=\(date)"         allow headers = ["Authorization": authorization]                      // straight off brand NSURLSession GET asking         allow session = URLSession(configuration: URLSessionConfiguration.ephemeral)         var asking = URLRequest(url: nsURL)         request.allHTTPHeaderFields = headers         request.httpMethod = "GET"         allow dataTask = session.dataTask(with: request, completionHandler: {(data, response, error) inwards             if (error != nil) {                 print("error")             }             if allow reply = reply as? HTTPURLResponse {                 print(response.statusCode)                 print(response.allHeaderFields)             }             if allow information = information {                 print(String(data: data, encoding: String.Encoding.utf8) ?? "Fail")             }         })         dataTask.resume()     }          } 
All that therefore changes is the URL, which nosotros tin alter depending on the information type requested. This agency a slight alteration to our action:
@IBAction func channelDataReceive(_ sender: Any) {     allow channelID = ""     allow keyID = ""     allow cloak-and-dagger = ""      channelData(type:.Data, channelID: channelID, apiKeyID: keyID, apiKeySecret: secret) } 
And a repetition of this method for each push clit changing the type – or a tagging (or reading of the) buttons, approach it how you lot volition – simply know that for retrieving sections you lot role the .Section instance too for articles the .Article instance too all volition hold out well.

I promise to render to this theme too presently focus on uploading articles using Swift. Meanwhile hither are some handy links:

Tools

News Preview app (Apple)

Guides

News Publishing Guide (Apple)
Formatting Guide (Apple)
API Reference (Apple)

Examples

Example Articles (Apple, run across bottom of page)

Resources

Apple News Resources too Contact (Apple)

Comments

Popular posts from this blog

What Are The Main Components of a Computer System

Top Qualities To Look For In An IT Support Team

How To Integrate Google Adwords Api Into Codeigniter?