Updating from an API

The following is a snippet showing how to takes parts of a Lightwell document, update them with data from an api call, and trigger animations to preset a promotional popup.

This snippet uses the exported assets here, and presents the contents inside of a view controller. To try out the code download the assets and include them inside of an xcode project. For a detailed walkthrough of the snippet, check out the Updating from an API Walkthrough.

importUIKitimportHullabaluStoryKitclassViewController:UIViewController{// 1) Initialize the loading context for the promo popupletcontext=LWKLoadingContext(screenName:"promo")overridefuncviewDidAppear(_animated:Bool){super.viewDidAppear(animated)self.getRemoteData()}funcgetRemoteData(){guardleturl=URL(string:"https://s3.amazonaws.com/lightwell/docs/sample/promo-api.json")else{return}varrequest=URLRequest(url:url)request.httpMethod="GET"lettask=URLSession.shared.dataTask(with:request){(data,response,error)inguardletdata=data,error==nilelse{// Failed to get dataifleterror=error{print(error)}return}// Parse dataguardletparsedData=try?JSONSerialization.jsonObject(with:data,options:[]),letusableData=parsedDataas?[String:String]else{// Failed to read datareturn}// Since we are updating the UI, this will need to be performed on the main thread.DispatchQueue.main.async{// Only grab the views we care about in the design from Lightwell.// 2) Add overlay to screenifletbackground=self.context?.view(for:"background"){background.frame=self.view.boundsself.view.addSubview(background)}// 3) Add popup to screenifletpopup=self.context?.view(for:"popup"){self.view.addSubview(popup)}// 4) Update contents based on response// Option 1 Update text ignoring styleifletbuttonTitle=usableData["button"]{(self.context?.view(for:"button title")as?UILabel)?.text=buttonTitle}// Option 2 Manually update text preserving styleiflettitle=usableData["title"]{ifletcurrentAttributes=(self.context?.view(for:"title")as?UILabel)?.attributedText{letattributedText=NSMutableAttributedString(attributedString:currentAttributes)attributedText.mutableString.setString(title)(self.context?.view(for:"title")as?UILabel)?.attributedText=attributedText}}// Option 3 Use a convenience function for updating text preserving style(self.context?.view(for:"copy")as?UILabel)?.setText(usableData["copy"],keepingAttributes:true)// 5) Add inputs to respond to promoself.context?.view(for:"background")?.addGestureRecognizer(UITapGestureRecognizer(target:self,action:#selector(self.dismissPopup)))self.context?.view(for:"button")?.addGestureRecognizer(UITapGestureRecognizer(target:self,action:#selector(self.respondToButton)))ifletrawImageURL=usableData["image url"],letimageUrl=URL(string:rawImageURL){letimageDownloadTask=URLSession.shared.dataTask(with:imageUrl){(data,response,error)inguardletdata=data,letimage=UIImage(data:data)else{// Failed to get imageifleterror=error{print(error)}else{print("Unable to read data as image.")}return}DispatchQueue.main.async{// Update image content(self.context?.view(for:"image")as?UIImageView)?.image=image// 6.a) Show the popup by running the animation actionself.context?.action(for:"show popup")?.run()}}imageDownloadTask.resume()}else{// 6.b) Show the popup by running the animation actionself.context?.action(for:"show popup")?.run()}}}task.resume()}@objcfuncdismissPopup(){// Hide the popup and backgroundcontext?.action(for:"dismiss popup")?.run()}@objcfuncrespondToButton(){// Play 'success' animationcontext?.action(for:"follow button")?.delegate=selfcontext?.action(for:"follow button")?.run()}}extensionViewController:LWKActionDelegate{funcactionDidEnd(_action:LWKAction,finished:Bool){// Follow buttonprint("decided to follow button")}}

The API is currently in beta and everything inside of these docs will be changing to improve the SDK. If there is a change you’d like to see or have any feedback, please email us at dev@lightwell.pro.