Beispiel #1
0
        protected override byte[] GetRawContentFromFileStream(string filePath)
        {
            SystemLogger.Log(SystemLogger.Module.PLATFORM, "# IPhoneResourceHandler. Getting Raw Content From FileStream on file path: " + filePath);

            // assuming that this method is just called for accessing web resources
            return(IPhoneUtils.GetInstance().GetResourceAsBinary(filePath, true));
        }
 protected override string readFromPlistFile(string file, string key)
 {
     if (IPhoneUtils.GetInstance().ResourcesZipped)
     {
         // if resource is zipped, we will need to parse the file as an xml file (done in abstract class)
         return(base.readFromPlistFile(file, key));
     }
     else
     {
         string result = string.Empty;
         if (this.FileExists(file))
         {
             NSDictionary resourcesLiteral = loadResourcesLiteral(file);
             if (resourcesLiteral != null)
             {
                 result = getResourceLiteralValue(key, file, resourcesLiteral);
             }
             result = (result == null || result == string.Empty) ? String.Format("<{0}>", key) : result;
         }
         else
         {
             // if file does not exists, means that requested locale is not supported by application
             // try then to get default locale string
             return(this.GetResourceLiteral(key));
         }
         return(result);
     }
 }
Beispiel #3
0
        /// <summary>
        /// Updates the module.
        /// </summary>
        /// <param name="module">Module.</param>
        /// <param name="callbackId">An identifier to be returned on the event listener in order to identify this request.</param>
        public override void UpdateModule(Module module, string callbackId)
        {
            List <Module> successlist = new List <Module> ();
            List <Module> failedlist  = new List <Module> ();

            // show activity indicator
            this.GetNotificationService().StartNotifyActivity();
            this.GetNotificationService().StartNotifyLoading(this.GetLocalizedMessage(DEFAULT_LOADING_MESSAGE_UPDATE_MODULE));

            if (module != null)
            {
                bool success = this.UpdateOrInstallModule(module);
                if (success)
                {
                    SystemLogger.Log(SystemLogger.Module.PLATFORM, "The module [ " + module.Id + "] was successfully updated");
                    successlist.Add(module);
                }
                else
                {
                    SystemLogger.Log(SystemLogger.Module.PLATFORM, "The module [ " + module.Id + "] was NOT successfully updated");
                    failedlist.Add(module);
                }
            }

            UIApplication.SharedApplication.InvokeOnMainThread(delegate {
                IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Appverse.AppLoader.onUpdateModulesFinished",
                                                                   new object [] { successlist.ToArray(), failedlist.ToArray(), callbackId });
            });

            // hide activity indicator
            this.GetNotificationService().StopNotifyActivity();
            this.GetNotificationService().StopNotifyLoading();
        }
Beispiel #4
0
 public override void CancelLocalNotification(DateTime fireDate)
 {
     UIApplication.SharedApplication.InvokeOnMainThread(delegate {
         int numScheduledLocalNotifications = this.GetCurrentScheduledLocalNotifications();
         if (numScheduledLocalNotifications <= 0)
         {
             SystemLogger.Log(SystemLogger.Module.PLATFORM, "No scheduled local notifications found. It is not possible to cancel the one requested");
         }
         else
         {
             SystemLogger.Log(SystemLogger.Module.PLATFORM, "(1) Current scheduled #num of local notifications: " + numScheduledLocalNotifications);
             NSDate fireDateNS = IPhoneUtils.DateTimeToNSDate(DateTime.SpecifyKind(fireDate, DateTimeKind.Local));
             SystemLogger.Log(SystemLogger.Module.PLATFORM, "Checking local notification to be cancelled, scheduled at " + fireDateNS.ToString());
             foreach (UILocalNotification notification in UIApplication.SharedApplication.ScheduledLocalNotifications)
             {
                 if (notification.FireDate.SecondsSinceReferenceDate == fireDateNS.SecondsSinceReferenceDate)
                 {
                     SystemLogger.Log(SystemLogger.Module.PLATFORM, "Cancelling notification scheduled at: " + notification.FireDate.ToString());
                     UIApplication.SharedApplication.CancelLocalNotification(notification);
                     SystemLogger.Log(SystemLogger.Module.PLATFORM, "Cancelled");
                 }
             }
             SystemLogger.Log(SystemLogger.Module.PLATFORM, "(2) Current scheduled #num of local notifications: " + this.GetCurrentScheduledLocalNotifications());
         }
     });
 }
Beispiel #5
0
        public override bool Play(string filePath)
        {
            // File path is relative path.
            string absolutePath = IPhoneUtils.GetInstance().GetFileFullPath(filePath);

            if (!File.Exists(absolutePath))
            {
                // file path was not under application bundle path
                // try to find it under Documents folder
                if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                {
                    var documents = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User) [0].Path;
                    absolutePath = Path.Combine(documents, filePath);
                }
                else
                {
                    var documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                    absolutePath = Path.Combine(documents, filePath);
                };
                //absolutePath = Path.Combine(IPhoneFileSystem.DEFAULT_ROOT_PATH, filePath);
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "Media file does not exist on bundle path, checking under application documents: " + absolutePath);
            }

            NSUrl nsUrl = this.GetNSUrlFromPath(absolutePath, true);

            return(this.PlayNSUrl(nsUrl));
        }
Beispiel #6
0
        public override void GetStoredKeyValuePairs(string[] keynames)
        {
            UIApplication.SharedApplication.InvokeOnMainThread(delegate {
                string sAccessGroup          = KeyChainAccessGroup;
                List <KeyPair> foundKeyPairs = new List <KeyPair>();
                foreach (string key in keynames)
                {
                    SecRecord srSearchCriteria = new SecRecord(SecKind.GenericPassword)
                    {
                        Account = key
                    };

                    if (sAccessGroup != null)
                    {
                        srSearchCriteria.AccessGroup = sAccessGroup;
                    }

                    SecStatusCode keyResult;
                    SecRecord srFoundKey = SecKeyChain.QueryAsRecord(srSearchCriteria, out keyResult);
                    if (keyResult == SecStatusCode.Success)
                    {
                        if (srFoundKey != null)
                        {
                            foundKeyPairs.Add(SecRecordToKeyPair(srFoundKey));
                        }
                    }
                }

                SystemLogger.Log(SystemLogger.Module.PLATFORM, "GetStoredKeyValuePairs - Found: " + foundKeyPairs.Count);

                IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Appverse.OnKeyValuePairsFound", foundKeyPairs);
            });
        }
Beispiel #7
0
        private NSUrl GetNSUrlFromPath(string path, bool localPath)
        {
            NSUrl nsUrl = null;

            SystemLogger.Log(SystemLogger.Module.PLATFORM, "Getting nsurl from path: " + path);
            try {
                if (localPath)
                {
                    // check resource from local file system
                    //nsUrl = NSUrl.FromFilename(path);
                    nsUrl = IPhoneUtils.GetInstance().GetNSUrlFromPath(path);
                }
                else
                {
                    // check remote resource.
                    // remote paths should be escaped using Uri format
                    path  = Uri.EscapeUriString(path);
                    nsUrl = NSUrl.FromString(path);
                    SystemLogger.Log(SystemLogger.Module.PLATFORM, "nsUrl from remote string: " + nsUrl);
                }
            } catch (Exception) {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "Error trying to get media file [" + path + "]");
            }

            return(nsUrl);
        }
 protected override ResourceLiteralDictionary readAllFromPlistFile(string file)
 {
     if (IPhoneUtils.GetInstance().ResourcesZipped)
     {
         // if resource is zipped, we will need to parse the file as an xml file (done in abstract class)
         return(base.readAllFromPlistFile(file));
     }
     else
     {
         ResourceLiteralDictionary result = null;
         if (this.FileExists(file))
         {
             result = new ResourceLiteralDictionary();
             NSDictionary literalDictionary = loadResourcesLiteral(file);
             foreach (NSObject key in literalDictionary.Keys)
             {
                 result.Add(key.ToString(), literalDictionary[key].ToString());
             }
             return(result);
         }
         else
         {
             // if file does not exists, means that requested locale is not supported by application
             // try then to get default locale string
             return(this.GetResourceLiterals());
         }
     }
 }
Beispiel #9
0
        public override void RemoveStoredKeyValuePairs(string[] keynames)
        {
            string        sAccessGroup        = KeyChainAccessGroup;
            List <string> successfullKeyPairs = new List <string>();
            List <string> failedKeyPairs      = new List <string>();

            UIApplication.SharedApplication.InvokeOnMainThread(delegate {
                foreach (string keyname in keynames)
                {
                    SecRecord srDeleteEntry = new SecRecord(SecKind.GenericPassword)
                    {
                        Account = keyname
                    };

                    if (sAccessGroup != null)
                    {
                        srDeleteEntry.AccessGroup = sAccessGroup;
                    }

                    SecStatusCode code = SecKeyChain.Remove(srDeleteEntry);
                    if (code == SecStatusCode.Success)
                    {
                        successfullKeyPairs.Add(keyname);
                    }
                    else
                    {
                        failedKeyPairs.Add(keyname);
                    }
                }
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "RemoveStoredKeyValuePair - Success: " + successfullKeyPairs.Count + ", Failed: " + failedKeyPairs.Count);

                IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Appverse.OnKeyValuePairsRemoveCompleted", new object[] { successfullKeyPairs, failedKeyPairs });
            });
        }
Beispiel #10
0
        private UILocalNotification PrepareLocalNotification(NotificationData notification)
        {
            if (notification != null)
            {
                UILocalNotification localNotification = new UILocalNotification();
                localNotification.AlertBody = notification.AlertMessage;
                localNotification.ApplicationIconBadgeNumber = notification.Badge;
                localNotification.SoundName = UILocalNotification.DefaultSoundName;                 // defaults
                if (notification.Sound != null && notification.Sound.Length > 0 && !notification.Sound.Equals("default"))
                {
                    // for sounds different from the default one
                    localNotification.SoundName = notification.Sound;
                }
                if (notification.CustomDataJsonString != null && notification.CustomDataJsonString.Length > 0)
                {
                    SystemLogger.Log(SystemLogger.Module.PLATFORM, "Custom Json String received: " + notification.CustomDataJsonString);

                    Dictionary <String, Object> userDictionary = (Dictionary <String, Object>)IPhoneUtils.GetInstance().JSONDeserialize <Dictionary <String, Object> >(notification.CustomDataJsonString);
                    localNotification.UserInfo = IPhoneUtils.GetInstance().ConvertToNSDictionary(userDictionary);
                }
                return(localNotification);
            }
            else
            {
                return(null);
            }
        }
Beispiel #11
0
        private byte[] GetResourceAsBinaryFromZipped(string resourcePath)
        {
            if (_zipFile != null)
            {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "# Loading resource from zipped file: " + resourcePath);
                //Stopwatch stopwatch = new Stopwatch();
                //stopwatch.Start();

                ZipEntry entry = this.GetZipEntry(resourcePath);                  // getting the entry from the _zipFile.GetEntry() method is less efficient
                if (entry != null)
                {
                    //SystemLogger.Log(SystemLogger.Module.PLATFORM, "# entry found [" + entry.Name + "]: " + entry.Size);

                    //long et1 = stopwatch.ElapsedMilliseconds;
                    Stream entryStream = _zipFile.GetInputStream(entry);

                    //long et2 = stopwatch.ElapsedMilliseconds;

                    // entryStream is not seekable, it should be first readed
                    byte[] data = IPhoneUtils.ConvertNonSeekableStreamToByteArray(entryStream);                     //, entry.Size
                    //SystemLogger.Log(SystemLogger.Module.PLATFORM, "# entry found [" + entry.Name + "], data byte array size:" + data.Length);

                    //long et3 = stopwatch.ElapsedMilliseconds;
                    //SystemLogger.Log(SystemLogger.Module.PLATFORM, "CSV," + resourcePath + "," + entry.Size + "," + entry.CompressedSize + ","+ et1 +","+(et2-et1)+","+(et3-et2)+","+(et3));
                    //stopwatch.Stop();
                    return(data);
                }

                //stopwatch.Stop();
            }

            return(null);
        }
Beispiel #12
0
 public bool ResourceExists(string resourcePath)
 {
     //SystemLogger.Log (SystemLogger.Module.PLATFORM, "# Checking file exists: " + resourcePath);
     if (this.ResourcesZipped)
     {
         return(IPhoneUtils.GetInstance().ResourceFromZippedExists(resourcePath));
     }
     else
     {
         return(File.Exists(resourcePath));
     }
 }
 protected override XmlTextReader getXmlTextReader(string textFilePath)
 {
     if (IPhoneUtils.GetInstance().ResourcesZipped)
     {
         Stream stream = IPhoneUtils.GetInstance().GetResourceAsStream(textFilePath);
         return(new XmlTextReader(stream));
     }
     else
     {
         return(base.getXmlTextReader(textFilePath));
     }
 }
        public override void StoreKeyValuePairs(KeyPair[] keypairs)
        {
            string         sAccessGroup        = KeyChainAccessGroup;
            List <KeyPair> successfullKeyPairs = new List <KeyPair>();
            List <KeyPair> failedKeyPairs      = new List <KeyPair>();

            foreach (KeyPair kp in keypairs)
            {
                SecRecord srNewEntry = new SecRecord(SecKind.GenericPassword)
                {
                    Account   = kp.Key,
                    Generic   = NSData.FromString(kp.Key),
                    ValueData = NSData.FromString(kp.Value)
                };

                if (sAccessGroup != null)
                {
                    srNewEntry.AccessGroup = sAccessGroup;
                }

                SecStatusCode code = SecKeyChain.Add(srNewEntry);
                if (code == SecStatusCode.DuplicateItem)
                {
                    SecRecord srDeleteExistingEntry = new SecRecord(SecKind.GenericPassword)
                    {
                        Account = kp.Key
                    };
                    if (sAccessGroup != null)
                    {
                        srDeleteExistingEntry.AccessGroup = sAccessGroup;
                    }
                    code = SecKeyChain.Remove(srDeleteExistingEntry);
                    if (code == SecStatusCode.Success)
                    {
                        SecKeyChain.Add(srNewEntry);
                    }
                }
                if (code == SecStatusCode.Success)
                {
                    successfullKeyPairs.Add(kp);
                }
                else
                {
                    failedKeyPairs.Add(kp);
                }
            }

            SystemLogger.Log(SystemLogger.Module.PLATFORM, "StoreKeyValuePairs - Success: " + successfullKeyPairs.Count + ", Failed: " + failedKeyPairs.Count);
            UIApplication.SharedApplication.InvokeOnMainThread(delegate {
                IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Unity.OnKeyValuePairsStoreCompleted", new object[] { successfullKeyPairs, failedKeyPairs });
            });
        }
Beispiel #15
0
        protected override string GetContentFromStreamReader(string filePath)
        {
            //return base.GetContentFromStreamReader(filePath);
            SystemLogger.Log(SystemLogger.Module.PLATFORM, "# IPhoneResourceHandler. Getting Content From StreamReader on file path: " + filePath);

            Stream sr = IPhoneUtils.GetInstance().GetResourceAsStream(filePath);

            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            string content = enc.GetString(((MemoryStream)sr).GetBuffer());

            sr.Close();

            return(content);
        }
Beispiel #16
0
        /// <summary>
        /// Deletes the modules.
        /// </summary>
        /// <param name="modules">Modules.</param>
        public override void DeleteModules(Module[] modules)
        {
            List <Module> successlist = new List <Module> ();
            List <Module> failedlist  = new List <Module> ();

            this.GetNotificationService().StartNotifyLoading(this.GetLocalizedMessage(DEFAULT_LOADING_MESSAGE_DELETE_MODULES));

            try {
                foreach (Module module in modules)
                {
                    bool moduleDeleted = false;
                    try {
                        string location      = this.GetModuleLocation(module, false);
                        string directoryName = Path.Combine(this.GetFileSystemService().GetDirectoryRoot().FullName, location);
                        SystemLogger.Log(SystemLogger.Module.PLATFORM, "Deleting module under: " + location);

                        if (Directory.Exists(directoryName))
                        {
                            Directory.Delete(directoryName, true);
                            moduleDeleted = true;
                        }
                        else
                        {
                            SystemLogger.Log(SystemLogger.Module.PLATFORM, "Module does not exists on filesystem. It couldn't be deleted.");
                        }
                    } catch (Exception ex) {
                        SystemLogger.Log(SystemLogger.Module.PLATFORM,
                                         "Exception when deleting module [" + (module != null?module.Id:"undefined") + "]: " + ex.Message);
                    }

                    if (moduleDeleted)
                    {
                        successlist.Add(module);
                    }
                    else
                    {
                        failedlist.Add(module);
                    }
                }
            } catch (Exception ex) {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "Exception when deleting modules: " + ex.Message);
            }
            UIApplication.SharedApplication.InvokeOnMainThread(delegate {
                IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Appverse.AppLoader.onDeleteModulesFinished",
                                                                   new object [] { successlist.ToArray(), failedlist.ToArray() });
            });

            this.GetNotificationService().StopNotifyLoading();
        }
Beispiel #17
0
 /// <summary>
 /// Sends the back result, by evaluating javascript inside UIWebview component (must be invoked on main thread)
 /// </summary>
 /// <param name='callbackFunction'>
 /// Callback function.
 /// </param>
 /// <param name='id'>
 /// Identifier.
 /// </param>
 /// <param name='jsonResultString'>
 /// Json result string.
 /// </param>
 protected override void SendBackResult(string callbackFunction, string id, string jsonResultString)
 {
     UIApplication.SharedApplication.InvokeOnMainThread(delegate {
         if (callbackFunction == null || callbackFunction.Equals("NULL"))
         {
             SystemLogger.Log(SystemLogger.Module.PLATFORM, " ############## There is no callback defined for sending back result to javascript app");
         }
         else
         {
             SystemLogger.Log(SystemLogger.Module.PLATFORM, " ############## sending back result to callback fn [" + callbackFunction + "] and id [" + id + "]: " +
                              (jsonResultString != null?jsonResultString.Length:0));
             IPhoneUtils.GetInstance().ExecuteJavascriptCallback(callbackFunction, id, jsonResultString);
         }
     });
 }
Beispiel #18
0
        public override MediaMetadata GetMetadata(string filePath)
        {
            string absolutePath = filePath;
            bool   localPath    = false;

            if (!absolutePath.StartsWith("http"))
            {
                // File path is relative path
                absolutePath = IPhoneUtils.GetInstance().GetFileFullPath(filePath);
                localPath    = true;
            }
            NSUrl nsUrl = this.GetNSUrlFromPath(absolutePath, localPath);

            return(this.GetMetadataFromUrl(nsUrl));
        }
Beispiel #19
0
 public override void ScheduleLocalNotification(NotificationData notification, SchedulingData schedule)
 {
     UIApplication.SharedApplication.InvokeOnMainThread(delegate {
         if (notification != null)
         {
             UILocalNotification localNotification = this.PrepareLocalNotification(notification);
             if (schedule != null)
             {
                 localNotification.FireDate = IPhoneUtils.DateTimeToNSDate(DateTime.SpecifyKind(schedule.FireDate, DateTimeKind.Local));
                 SystemLogger.Log(SystemLogger.Module.PLATFORM, "Scheduling local notification at "
                                  + schedule.FireDate.ToLongTimeString() + ", with a repeat interval of: " + schedule.RepeatInterval);
                 NSCalendarUnit repeatInterval = 0;                         // The default value is 0, which means don't repeat.
                 if (schedule.RepeatInterval.Equals(RepeatInterval.HOURLY))
                 {
                     repeatInterval = NSCalendarUnit.Hour;
                 }
                 else if (schedule.RepeatInterval.Equals(RepeatInterval.DAILY))
                 {
                     repeatInterval = NSCalendarUnit.Day;
                 }
                 else if (schedule.RepeatInterval.Equals(RepeatInterval.WEEKLY))
                 {
                     repeatInterval = NSCalendarUnit.Week;
                 }
                 else if (schedule.RepeatInterval.Equals(RepeatInterval.MONTHLY))
                 {
                     repeatInterval = NSCalendarUnit.Month;
                 }
                 else if (schedule.RepeatInterval.Equals(RepeatInterval.YEARLY))
                 {
                     repeatInterval = NSCalendarUnit.Year;
                 }
                 localNotification.RepeatInterval = repeatInterval;
                 UIApplication.SharedApplication.ScheduleLocalNotification(localNotification);
                 SystemLogger.Log(SystemLogger.Module.PLATFORM, "Local Notification scheduled successfully [" + localNotification.FireDate.ToString() + "]");
                 SystemLogger.Log(SystemLogger.Module.PLATFORM, "Current scheduled #num of local notifications: " + this.GetCurrentScheduledLocalNotifications());
             }
             else
             {
                 SystemLogger.Log(SystemLogger.Module.PLATFORM, "No suitable scheduling data object received for scheduling this local notification");
             }
         }
         else
         {
             SystemLogger.Log(SystemLogger.Module.PLATFORM, "No suitable data object received for presenting local notification");
         }
     });
 }
        public NSData ProcessDocumentResource(string resourcePath)
        {
            SystemLogger.Log(SystemLogger.Module.PLATFORM, "# IPhoneResourceHandler. Processing document resource path: " + resourcePath);

            // url should be escaped to reach the real filesystem path for the requested file.
            resourcePath = Uri.UnescapeDataString(resourcePath);

            // Getting Root Directory for Files in this platform.
            IFileSystem   fileSystemService = (IFileSystem)IPhoneServiceLocator.GetInstance().GetService("file");
            DirectoryData rootDir           = fileSystemService.GetDirectoryRoot();

            resourcePath = Path.Combine(rootDir.FullName, resourcePath);

            // Get Resources as Binary Data and Write them to the server response
            return(NSData.FromArray(IPhoneUtils.GetInstance().GetResourceAsBinary(resourcePath, false)));
        }
Beispiel #21
0
 void HandleImagePickerControllerCanceled(object sender, EventArgs e)
 {
     UIApplication.SharedApplication.InvokeOnMainThread(delegate {
         SystemLogger.Log(SystemLogger.Module.PLATFORM, "Canceled picking image ");
         IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Appverse.Media.onFinishedPickingImage", null);
         if (popover != null && popover.PopoverVisible)
         {
             popover.Dismiss(true);
             popover.Dispose();
         }
         else
         {
             IPhoneServiceLocator.CurrentDelegate.MainUIViewController().DismissModalViewController(true);
         }
     });
 }
Beispiel #22
0
        /// <summary>
        /// Starts local authentication operation displaying Touch ID screen.
        /// </summary>
        /// <param name="reason">A reason to explain why authentication is needed. This helps to build trust with the user.</param>
        public override void StartLocalAuthenticationWithTouchID(string reason)
        {
            SystemLogger.Log(SystemLogger.Module.PLATFORM, "StartLocalAuthenticationWithTouchID - starting authentication using Touch ID...");
            UIApplication.SharedApplication.InvokeOnMainThread(delegate {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "StartLocalAuthenticationWithTouchID - checking Touch ID available in this device");

                bool available = this.CanEvaluatePolicy();
                if (available)
                {
                    SystemLogger.Log(SystemLogger.Module.PLATFORM, "StartLocalAuthenticationWithTouchID - start device owner authenticaiton using biometrics");
                    this.EvaluatePolicy(reason);
                }
                else
                {
                    IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Appverse.Security.onTouchIDNotAvailable", null);
                }
            });
        }
Beispiel #23
0
        void HandleCameraFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs e)
        {
            UIApplication.SharedApplication.InvokeOnMainThread(delegate {
                IPhoneServiceLocator.CurrentDelegate.MainUIViewController().DismissModalViewController(true);
            });

            SystemLogger.Log(SystemLogger.Module.PLATFORM, "Camera FinishedPickingMedia " + e.Info);

            MediaMetadata mediaData = new MediaMetadata();

            try {
                NSString mediaType = (NSString)e.Info.ValueForKey(UIImagePickerController.MediaType);
                UIImage  image     = (UIImage)e.Info.ValueForKey(UIImagePickerController.OriginalImage);

                if (image != null && mediaType != null && mediaType == "public.image")                 // "public.image" is the default UTI (uniform type) for images.
                {
                    mediaData.Type     = MediaType.Photo;
                    mediaData.MimeType = MediaMetadata.GetMimeTypeFromExtension(".jpg");
                    mediaData.Title    = (image.GetHashCode() & 0x7FFFFFFF) + ".JPG";

                    NSData imageData = image.AsJPEG();

                    if (imageData != null)
                    {
                        SystemLogger.Log(SystemLogger.Module.PLATFORM, "Getting image data raw data...");

                        byte[] buffer = new byte[imageData.Length];
                        Marshal.Copy(imageData.Bytes, buffer, 0, buffer.Length);

                        IFileSystem fileSystemService = (IFileSystem)IPhoneServiceLocator.GetInstance().GetService("file");
                        SystemLogger.Log(SystemLogger.Module.CORE, "Storing media file on application filesystem...");

                        mediaData.ReferenceUrl = fileSystemService.StoreFile(IPhoneMedia.ASSETS_PATH, mediaData.Title, buffer);
                    }

                    SystemLogger.Log(SystemLogger.Module.PLATFORM, mediaData.MimeType + ", " + mediaData.ReferenceUrl + ", " + mediaData.Title);
                }
            } catch (Exception ex) {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "Error when extracting information from media file: " + ex.Message, ex);
            }

            IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Appverse.Media.onFinishedPickingImage", mediaData);
        }
Beispiel #24
0
        public static IPhoneUtils GetInstance()
        {
            if (singleton == null)
            {
                singleton = new IPhoneUtils();

                singleton.Serialiser = new JavaScriptSerializer();

                if (singleton.ResourcesZipped)
                {
                    // testing removing disk and memory cache capacity
                    SystemLogger.Log(SystemLogger.Module.PLATFORM, "# Removing cache disk and memory capacity");
                    NSUrlCache.SharedCache.DiskCapacity   = 0;
                    NSUrlCache.SharedCache.MemoryCapacity = 0;
                    singleton.LoadZippedFile();
                }
            }
            return(singleton);
        }
Beispiel #25
0
        public override bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            if (request.Url.StartsWith(DOCUMENTS_URI))
            {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, " ############## " + this.GetType() + " -> " + request.Url);

                string requestUrl = request.Url;
                if (request.QueryString != null && request.QueryString.Length > 0)
                {
                    requestUrl = request.Page;
                    SystemLogger.Log(SystemLogger.Module.PLATFORM, " ############## " + this.GetType() + " -> removing req params -> " + requestUrl);
                }

                string escapedUrl = Uri.UnescapeDataString(requestUrl);
                // url should be escaped to reach the real filesystem path for the requested file.
                string resourcePath = escapedUrl.Substring(DOCUMENTS_URI.Length);

                // Getting mime type
                string ext  = Path.GetExtension(resourcePath.ToLower());
                string mime = (string)MimeTypes [ext];
                if (mime == null)
                {
                    mime = "application/octet-stream";
                }
                response.ContentType = mime;

                // Getting Root Directory for Files in this platform.
                IFileSystem   fileSystemService = (IFileSystem)IPhoneServiceLocator.GetInstance().GetService("file");
                DirectoryData rootDir           = fileSystemService.GetDirectoryRoot();
                resourcePath = Path.Combine(rootDir.FullName, resourcePath);

                // Get Resources as Binary Data and Write them to the server response
                response.RawContent = IPhoneUtils.GetInstance().GetResourceAsBinary(resourcePath, false);
                SystemLogger.Log(SystemLogger.Module.PLATFORM, " ############## " + this.GetType() + " -> file extension: " + ext + ", mimetype: " + mime + ", binary data length: " + response.RawContent.Length);

                return(true);
            }
            else
            {
                return(base.Process(server, request, response));
            }
        }
Beispiel #26
0
        /// <summary>
        /// Method overrided, to start activity notification while invoking external service.
        /// </summary>
        /// <param name="request">
        /// A <see cref="IORequest"/>
        /// </param>
        /// <param name="service">
        /// A <see cref="IOService"/>
        /// </param>
        /// <returns>
        /// A <see cref="IOResponse"/>
        /// </returns>
        public override IOResponse InvokeService(IORequest request, IOService service)
        {
            this.IOUserAgent = IPhoneUtils.GetInstance().GetUserAgent();
            INotification notificationService = (INotification)IPhoneServiceLocator.GetInstance().GetService("notify");

            try {
                notificationService.StartNotifyActivity();
            } catch (Exception e) {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "Cannot StartNotifyActivity. Message: " + e.Message);
            }
            IOResponse response = base.InvokeService(request, service);

            try {
                notificationService.StopNotifyActivity();
            } catch (Exception e) {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "Cannot StopNotifyActivity. Message: " + e.Message);
            }

            return(response);
        }
Beispiel #27
0
        private void ShowActionSheet(object sheet)
        {
            ActionSheet actionSheet = (ActionSheet)sheet;

            UIApplication.SharedApplication.InvokeOnMainThread(delegate {
                if (actionSheet.Title == null)
                {
                    actionSheet.Title = "";                     // null value cannot be passed to UIActionSheet constructor.
                }

                string cancelButton = null;
                string[] buttons    = new string[0];

                if (IPhoneUtils.GetInstance().IsIPad())
                {
                    // For iPad, cancelButton cannot be specified. It has to be included as an "other" button.
                    buttons = actionSheet.Buttons;
                }
                else
                {
                    if (actionSheet.Buttons != null && actionSheet.Buttons.Length > 0)
                    {
                        buttons      = new string[actionSheet.Buttons.Length - 1];
                        cancelButton = actionSheet.Buttons[0];
                        for (int i = 1; i < actionSheet.Buttons.Length; i++)
                        {
                            buttons[i - 1] = actionSheet.Buttons[i];
                        }
                    }
                    else
                    {
                        // default
                        cancelButton = "Cancel";
                    }
                }

                UIActionSheet uiSheet = new UIActionSheet(actionSheet.Title, new ActionSheetDelegate(actionSheet.JsCallbackFunctions), cancelButton, null, buttons);
                uiSheet.ShowInView(IPhoneServiceLocator.CurrentDelegate.MainUIViewController().View);
            });
        }
Beispiel #28
0
        private void HandleLAContextReplyHandler(bool success, NSError error)
        {
            string message                   = success ? "EvaluatePolicy success" : string.Format("EvaluatePolicy: failed with error: {0}", error.LocalizedDescription);
            string errorDescription          = "Authentication Success";
            LocalAuthenticationStatus status = LocalAuthenticationStatus.Success;

            if (!success)
            {
                errorDescription = error.LocalizedDescription;
                switch (error.Code)
                {
                case 0:
                    status = LocalAuthenticationStatus.Success;
                    break;

                case -1:
                    status = LocalAuthenticationStatus.RetryExceeded;
                    break;

                case -2:
                    status = LocalAuthenticationStatus.UserCancel;
                    break;

                case -3:
                    status = LocalAuthenticationStatus.UserFallback;
                    break;

                default:
                    SystemLogger.Log(SystemLogger.Module.PLATFORM, "HandleLAContextReplyHandler - found not handled error code: " + error.Code);
                    break;
                }
            }

            SystemLogger.Log(SystemLogger.Module.PLATFORM, "HandleLAContextReplyHandler - " + message);

            UIApplication.SharedApplication.InvokeOnMainThread(delegate {
                IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Appverse.Security.onLocalAuthenticationWithTouchIDReply", new object[] { status, errorDescription });
            });
        }
Beispiel #29
0
        private void ShowImagePickerView()
        {
            UIApplication.SharedApplication.InvokeOnMainThread(delegate {
                UIImagePickerController imagePickerController = new UIImagePickerController();
                imagePickerController.FinishedPickingImage   += HandleImagePickerControllerFinishedPickingImage;
                imagePickerController.FinishedPickingMedia   += HandleImagePickerControllerFinishedPickingMedia;
                imagePickerController.Canceled += HandleImagePickerControllerCanceled;


                if (IPhoneUtils.GetInstance().IsIPad())
                {
                    try {
                        // in iPad, the UIImagePickerController should be presented inside a UIPopoverController, otherwise and exception is raised
                        popover     = new UIPopoverController(imagePickerController);
                        UIView view = IPhoneServiceLocator.CurrentDelegate.MainUIViewController().View;
                        //CGRect frame = new CGRect(new PointF(0,0),new SizeF(view.Frame.Size.Width, view.Frame.Size.Height));
                        CGRect frame = new CGRect(new PointF(0, 0), new SizeF(0, 0));
                        popover.PresentFromRect(frame, view, UIPopoverArrowDirection.Up, true);
                    }catch (Exception ex) {
                        INotification notificationService = (INotification)IPhoneServiceLocator.GetInstance().GetService("notify");
                        if (notificationService != null)
                        {
                            notificationService.StartNotifyAlert("Media Alert", "Unable to reach Photo Library", "OK");
                        }
                        if (popover != null && popover.PopoverVisible)
                        {
                            popover.Dismiss(true);
                            popover.Dispose();
                        }
                    }
                }
                else
                {
                    IPhoneServiceLocator.CurrentDelegate.MainUIViewController().PresentModalViewController(imagePickerController, true);
                }
            });
        }
        public override void DetectQRCode(bool autoHandleQR)
        {
            String returnValue = String.Empty;

            UIApplication.SharedApplication.InvokeOnMainThread(delegate {
                MobileBarcodeScanner scanner = new MobileBarcodeScanner(IPhoneServiceLocator.CurrentDelegate.MainUIViewController());
                scanner.Scan().ContinueWith(t => {
                    if (t.Result != null)
                    {
                        MediaQRContent resultQRContent = new MediaQRContent(t.Result.Text, ZxingToBarcode(t.Result.BarcodeFormat), getQRTypeFromCode(t.Result));
                        //SystemLogger.Log(SystemLogger.Module.PLATFORM, "QR CODE returnValue: " + resultQRContent);

                        UIApplication.SharedApplication.InvokeOnMainThread(delegate {
                            IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Unity.Media.onQRCodeDetected", resultQRContent);
                            if (autoHandleQR)
                            {
                                HandleQRCode(resultQRContent);
                            }
                        });
                    }
                });
                IPhoneServiceLocator.CurrentDelegate.SetMainUIViewControllerAsTopController(false);
            });
        }