Implement document drag to application in macOS using swift - swift

I am trying to associate a certain filename extension with my macOS application, which I have managed to do by following this guide and can drag my file in to my application.
When I drag my file in, I get this exception in the console:
2017-11-06 09:56:23.944202+0000 Test App[64192:2356795] [General] readFromData:ofType:error: is a subclass responsibility but has not been overridden.
2017-11-06 09:56:23.958166+0000 Test App[64192:2356795] [General] (
0 CoreFoundation 0x00007fff45f560fb exceptionPreprocess + 171
1 libobjc.A.dylib 0x00007fff6c844c76 objc_exception_throw + 48
2 CoreFoundation 0x00007fff45fe7bfd +[NSException raise:format:] + 205
3 AppKit 0x00007fff43a0b860 -[NSDocument readFromData:ofType:error:] + 253
4 AppKit 0x00007fff43a0b544 -[NSDocument readFromURL:ofType:error:] + 620
5 AppKit 0x00007fff436eb9b9 -[NSDocument _initWithContentsOfURL:ofType:error:] + 172
6 AppKit 0x00007fff436eb89e -[NSDocument initWithContentsOfURL:ofType:error:] + 231
7 AppKit 0x00007fff437c12dd -[NSDocumentController makeDocumentWithContentsOfURL:ofType:error:] + 628
8 AppKit 0x00007fff43a42578 __97-[NSDocumentController makeDocumentWithContentsOfURL:alternateContents:ofType:completionHandler:]_block_invoke + 91
9 AppKit 0x00007fff43a42512 -[NSDocumentController makeDocumentWithContentsOfURL:alternateContents:ofType:completionHandler:] + 176
10 AppKit 0x00007fff437c0493 __80-[NSDocumentController openDocumentWithContentsOfURL:display:completionHandler:]_block_invoke + 880
11 AppKit 0x00007fff43a411b9 __144-[NSDocumentController _coordinateReadingAndGetAlternateContentsForOpeningDocumentAtURL:resolvingSymlinks:thenContinueOnMainThreadWithAccessor:]_block_invoke_4 + 31
12 AppKit 0x00007fff43a41542 __144-[NSDocumentController _coordinateReadingAndGetAlternateContentsForOpeningDocumentAtURL:resolvingSymlinks:thenContinueOnMainThreadWithAccessor:]_block_invoke_2.970 + 149
13 AppKit 0x00007fff43a4147d __144-[NSDocumentController _coordinateReadingAndGetAlternateContentsForOpeningDocumentAtURL:resolvingSymlinks:thenContinueOnMainThreadWithAccessor:]_block_invoke.969 + 138
14 AppKit 0x00007fff43a4133f __144-[NSDocumentController _coordinateReadingAndGetAlternateContentsForOpeningDocumentAtURL:resolvingSymlinks:thenContinueOnMainThreadWithAccessor:]_block_invoke.964 + 254
15 CoreFoundation 0x00007fff45eee52c __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK + 12
16 CoreFoundation 0x00007fff45ed0f43 __CFRunLoopDoBlocks + 275
17 CoreFoundation 0x00007fff45ed0d08 __CFRunLoopRun + 3128
18 CoreFoundation 0x00007fff45ecfe43 CFRunLoopRunSpecific + 483
19 HIToolbox 0x00007fff451ef866 RunCurrentEventLoopInMode + 286
20 HIToolbox 0x00007fff451ef5d6 ReceiveNextEventCommon + 613
21 HIToolbox 0x00007fff451ef354 _BlockUntilNextEventMatchingListInModeWithFilter + 64
22 AppKit 0x00007fff434ec9f7 _DPSNextEvent + 2085
23 AppKit 0x00007fff43c81d98 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 3044
24 AppKit 0x00007fff434e1805 -[NSApplication run] + 764
25 AppKit 0x00007fff434b09a6 NSApplicationMain + 804
26 Test App 0x000000010004cd1d main + 13
27 libdyld.dylib 0x00007fff6d433145 start + 1
28 ??? 0x0000000000000003 0x0 + 3
I've tried implementing the NSApplicationDelegate openFile functions but none of them are called when I drag the file on to the app:
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func application(_ application: NSApplication, open urls: [URL]) {
}
func application(_ sender: NSApplication, openFile filename: String) -> Bool {
return false
}
func application(_ sender: NSApplication, openFiles filenames: [String]) {
}
func application(_ sender: NSApplication, openTempFile filename: String) -> Bool {
return false
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
How do I get access to the filename and contents of the "dragged in" file? I am using XCode 9.0.1 and Swift 4.
Edit:
Here is my Info.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>tal</string>
</array>
<key>CFBundleTypeIconFile</key>
<string></string>
<key>CFBundleTypeMIMETypes</key>
<array>
<string></string>
</array>
<key>CFBundleTypeName</key>
<string>Layout File</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>com.testapp.layout</string>
</array>
<key>LSTypeIsPackage</key>
<integer>0</integer>
<key>NSDocumentClass</key>
<string>NSDocument</string>
</dict>
</array>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>v1.0.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string></string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.video</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2017. All rights reserved.</string>
<key>NSMainStoryboardFile</key>
<string>Main</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.data</string>
</array>
<key>UTTypeDescription</key>
<string>Layout File</string>
<key>UTTypeIconFile</key>
<string></string>
<key>UTTypeIdentifier</key>
<string>com.testapp.layout</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>tal</string>
</array>
</dict>
</dict>
<dict/>
</array>
</dict>
</plist>
So I would have expected application(_ sender: NSApplication, openFile filename: String) to be called when I drag the file on to the app when it's in the Dock...

There are a number of points here to address:
if you're working in macOS 10.12 or below, you should implement either openFile or openFiles. openURLs is 10.13+ - but you definitely don't need both
openFile will be called for each of multiple files; if openFiles is present, openFile will not be called, even if you open only a single file
I have no idea what openTempFile (or openUntitledFile) are about; I haven't been able to get anyone to call either
openFile(s) get called when you have successfully registered a UTI with the system; double-clicking an appropriate file(s) in the Finder, choosing 'open' or dragging the file onto the dock icon of your app all send an open message that gets handled by the AppDelegate.
I am not clear what you mean by 'When I drag my file in': if you drag your file onto the app icon in the Finder, openFile(s) should be called; your wording makes me think that your drag destination is part of your application's interface, in which case you need to handle dragging yourself.
Also check - because the linked (iOS) guide does not address this - that you have set your NSDocument class: your example says 'NSDocument', but there is an extreme likelihood that your application uses a custom subclass; so you need to set the 'Class' to that name.

Related

permission_handler not asking for location

I'm using the permission_handler package for flutter. I'm successfully asking for the permissions on the camera, camera roll and the microphone.
But there is nothing popping up that asks me for the location.
I'm using this snippet to ask for the permission in my onboarding screen:
Map<Permission, PermissionStatus> statuses = await [
Permission.location,
Permission.storage,
Permission.camera,
Permission.photos,
Permission.microphone,
].request().whenComplete(() {
print('Permission.location.status');
print(Permission.location.status);
///load main
_onIntroEnd(context);
});
This is the post_install in my podfile
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |config|
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '11.0'
# You can enable the permissions needed here. For example to enable camera
# permission, just remove the `#` character in front so it looks like this:
#
# ## dart: PermissionGroup.camera
# 'PERMISSION_CAMERA=1'
#
# Preprocessor definitions can be found in: https://github.com/Baseflow/flutter-permission-handler/blob/master/permission_handler/ios/Classes/PermissionHandlerEnums.h
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
'$(inherited)',
## dart: PermissionGroup.calendar
# 'PERMISSION_EVENTS=1',
## dart: PermissionGroup.reminders
# 'PERMISSION_REMINDERS=1',
## dart: PermissionGroup.contacts
# 'PERMISSION_CONTACTS=1',
## dart: PermissionGroup.camera
'PERMISSION_CAMERA=1',
## dart: PermissionGroup.microphone
'PERMISSION_MICROPHONE=1',
## dart: PermissionGroup.speech
# 'PERMISSION_SPEECH_RECOGNIZER=1',
## dart: PermissionGroup.photos
'PERMISSION_PHOTOS=1',
## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
'PERMISSION_LOCATION=1',
## dart: PermissionGroup.notification
# 'PERMISSION_NOTIFICATIONS=1',
## dart: PermissionGroup.mediaLibrary
# 'PERMISSION_MEDIA_LIBRARY=1',
## dart: PermissionGroup.sensors
# 'PERMISSION_SENSORS=1',
## dart: PermissionGroup.bluetooth
# 'PERMISSION_BLUETOOTH=1',
## dart: PermissionGroup.appTrackingTransparency
# 'PERMISSION_APP_TRACKING_TRANSPARENCY=1'
]
end
end
end
and this is my info.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>WunderKlub</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>io.flutter.embedded_views_preview</key>
<true/>
<!-- Permission options for the `camera` group -->
<key>NSCameraUsageDescription</key>
<string>WunderKlub macht nur Spass mit Kamera.</string>
<!-- Permission options for the `microphone` group -->
<key>NSMicrophoneUsageDescription</key>
<string>Das Mikro nutzt WunderKlub gar nicht, es muss aber trotzdem abgefragt werden.</string>
<!-- Permission options for the `photos` group -->
<key>NSPhotoLibraryUsageDescription</key>
<string>WunderKlub möchte deine Fotos speichern können.</string>
<!-- Permission options for the `location` group -->
<key>NSLocationWhenInUseUsageDescription</key>
<string>Need location when in use</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Always and when in use!</string>
<key>NSLocationUsageDescription</key>
<string>Older devices need location.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Can I have location always?</string>
</dict>
</plist>
This was very strange, in the end I restarted my Mac and my IPhone and it worked. Sometimes it is as simple as that.

Mac OS AVPlayer Xcode 10.2.1 swift 5.0.1 won't work

I am trying to create a simple AVBasicPlayBack for Mac OS 10.14.5 Xcode 10.2.1 swift 5.0.1. I used AVPlayer it is throwing some errors. New to Mac OS Development could not figure out what is wrong. I have checked lots of documentation online.
I added NSAppTransportSecurity to info.plist file shown below.
info.plist file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2019 Personal. All rights reserved.</string>
<key>NSMainStoryboardFile</key>
<string>Main</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>devimages-cdn.apple.com</key>
<dict/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</dict>
</plist>
ViewController.swift
import Cocoa
import AVKit
class ViewController: NSViewController {
#IBOutlet weak var playerView: AVPlayerView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
guard let url = URL(string: "https://devimages-cdn.apple.com/samplecode/avfoundationMedia/AVFoundationQueuePlayer_HLS2/master.m3u8")
else {
return
}
// Create a new AVPlayer and associate it with the player view
//let player = AVPlayer(url: url)
//playerView.player = player
let avAsset = AVURLAsset(url: url, options: nil)
let playerItem = AVPlayerItem(asset: avAsset)
let videoPlayer = AVPlayer(playerItem: playerItem)
playerView.player = videoPlayer
videoPlayer.play()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
I get the following errors
2019-06-23 14:03:10.958123-0700 AVBasicPlayback[27278:6522581] [] nw_dictionary_set_value called with null dictionary
2019-06-23 14:03:10.958154-0700 AVBasicPlayback[27278:6522581] [] __nwlog_err_simulate_crash simulate crash failed "nw_dictionary_set_value called with null dictionary"
2019-06-23 14:03:10.958334-0700 AVBasicPlayback[27278:6522581] [] nw_dictionary_set_value called with null dictionary, dumping backtrace:
[x86_64] libnetcore-1229.250.15
0 libnetwork.dylib 0x00007fff747f8c88 __nw_create_backtrace_string + 120
1 libnetwork.dylib 0x00007fff7454cb09 nw_dictionary_set_value + 265
2 libnetwork.dylib 0x00007fff745e5bce nw_path_evaluator_cancel + 654
3 MediaToolbox 0x00007fff4e8ca975 FigMetadataReaderCreateForBoxedMetadata + 10998
4 MediaToolbox 0x00007fff4ea170f3 FigBytePumpCreateForHTTPChunk + 73903
5 MediaToolbox 0x00007fff4ea06752 FigBytePumpCreateForHTTPChunk + 5902
6 libdispatch.dylib 0x000000010034bf1b _dispatch_client_callout + 8
7 libdispatch.dylib 0x0000000100354067 _dispatch_lane_serial_drain + 773
8 libdispatch.dylib 0x0000000100354f4e _dispatch_lane_invoke + 493
9 libdispatch.dylib 0x000000010035e824 _dispatch_root_queue_drain + 334
10 libdispatch.dylib 0x000000010035e60b _dispatch_worker_thread + 271
11 libsystem_pthread.dylib 0x00000001003c5dc3 _pthread_body + 126
12 libsystem_pthread.dylib 0x00000001003c8e8d _pthread_start + 66
13 libsystem_pthread.dylib 0x00000001003c4e11 thread_start + 13
2019-06-23 14:03:10.964828-0700 AVBasicPlayback[27278:6522533] startConfigurationWithCompletionHandler: Failed to get remote object proxy: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.rtcreportingd" UserInfo={NSDebugDescription=connection to service named com.apple.rtcreportingd}
2019-06-23 14:03:10.973122-0700 AVBasicPlayback[27278:6522533] startConfigurationWithCompletionHandler: Failed to get remote object proxy: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.rtcreportingd" UserInfo={NSDebugDescription=connection to service named com.apple.rtcreportingd}
2019-06-23 14:03:10.982169-0700 AVBasicPlayback[27278:6522553] Received XPC error Connection invalid for message type 3 kCFNetworkAgentXPCMessageTypePACQuery
2019-06-23 14:03:10.982216-0700 AVBasicPlayback[27278:6522553] PAC result block not invoked
2019-06-23 14:03:10.982273-0700 AVBasicPlayback[27278:6522553] [] nw_proxy_resolver_create_parsed_array PAC evaluation error: kCFErrorDomainCFNetwork: 308
2019-06-23 14:03:10.984342-0700 AVBasicPlayback[27278:6522553] dnssd_clientstub ConnectToServer: connect()-> No of tries: 1
2019-06-23 14:03:11.988908-0700 AVBasicPlayback[27278:6522553] dnssd_clientstub ConnectToServer: connect()-> No of tries: 2
2019-06-23 14:03:12.990000-0700 AVBasicPlayback[27278:6522553] dnssd_clientstub ConnectToServer: connect()-> No of tries: 3
2019-06-23 14:03:13.995302-0700 AVBasicPlayback[27278:6522553] dnssd_clientstub ConnectToServer: connect() failed path:/var/run/mDNSResponder Socket:11 Err:-1 Errno:1 Operation not permitted
2019-06-23 14:03:13.996203-0700 AVBasicPlayback[27278:6522553] [] nw_resolver_create_dns_service_locked [C1.1] DNSServiceCreateDelegateConnection failed: ServiceNotRunning(-65563)
2019-06-23 14:03:13.997244-0700 AVBasicPlayback[27278:6522553] TIC TCP Conn Failed [1:0x600003716280]: 10:-72000 Err(-65563)
2019-06-23 14:03:13.998574-0700 AVBasicPlayback[27278:6522520] Task <B5B5187F-14BA-498B-91F3-630EE49FBFC0>.<1> HTTP load failed (error code: -1003 [10:-72000])
2019-06-23 14:03:13.998782-0700 AVBasicPlayback[27278:6522520] Task <B5B5187F-14BA-498B-91F3-630EE49FBFC0>.<1> finished with error - code: -1003
2019-06-23 14:03:14.005116-0700 AVBasicPlayback[27278:6522581] Task <B5B5187F-14BA-498B-91F3-630EE49FBFC0>.<1> load failed with error Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname could not be found." UserInfo={_kCFStreamErrorCodeKey=-72000, NSUnderlyingError=0x600000cdc270 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)" UserInfo={_kCFStreamErrorCodeKey=-72000, _kCFStreamErrorDomainKey=10}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <B5B5187F-14BA-498B-91F3-630EE49FBFC0>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <B5B5187F-14BA-498B-91F3-630EE49FBFC0>.<1>"
), NSLocalizedDescription=A server with the specified hostname could not be found., NSErrorFailingURLStringKey=https://devimages-cdn.apple.com/samplecode/avfoundationMedia/AVFoundationQueuePlayer_HLS2/master.m3u8, NSErrorFailingURLKey=https://devimages-cdn.apple.com/samplecode/avfoundationMedia/AVFoundationQueuePlayer_HLS2/master.m3u8, _kCFStreamErrorDomainKey=10} [-1003]
2019-06-23 14:03:14.007457-0700 AVBasicPlayback[27278:6522520] sendMessageWithDictionary: Failed to get remote object proxy: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.rtcreportingd" UserInfo={NSDebugDescription=connection to service named com.apple.rtcreportingd}
Select "Outgoing Connections (Client)" checkbox in "App Capabilities". This started displaying video but still some errors. I will update answer after I find solution for the remaining errors. Errors are regarding XPC.

SSLHandshake failed with Error code -9801 on Alamofire 3.1.2, XCode 7.1, iOS 9

I did the following upgrades to my Swift project
iOS 9, XCode 7.1, El Captain
Alamofire 1.3 -> 3.1.2
I get the following error while connecting to a self signed (test) web service.
Error Message
2015-11-12 21:46:13.045 [72695:5258083] CFNetwork SSLHandshake failed
(-9801) 2015-11-12 21:46:13.046 [72695:5258083]
NSURLSession/NSURLConnection HTTP load failed
(kCFStreamErrorDomainSSL, -9801) 2015-11-12 21:46:13.051 [Error]
[DeviceInfo.swift:277] generateUserToken > Error while processing
generateUserToken() : Optional(Error Domain=NSURLErrorDomain
Code=-1200 "An SSL error has occurred and a secure connection to the
server cannot be made." UserInfo={_kCFStreamErrorCodeKey=-9801,
NSLocalizedRecoverySuggestion=Would you like to connect to the server
anyway?, NSUnderlyingError=0x7ffa99a0b8c0 {Error
Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)"
UserInfo={_kCFStreamPropertySSLClientCertificateState=0,
_kCFNetworkCFStreamSSLErrorOriginalValue=-9801, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9801}}, NSLocalizedDescription=An SSL error has occurred and a secure
connection to the server cannot be made.,
I have implemented the below code to disable SSL validation as per https://github.com/Alamofire/Alamofire#security
class CustomServerTrustPolicyManager: ServerTrustPolicyManager {
override func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? {
var policy: ServerTrustPolicy?
policy = ServerTrustPolicy.DisableEvaluation
return policy
}
}
public class NetworkManager {
static let sharedInstace = NetworkManager()
let defaultManager : Manager = {
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"myservice.com": .DisableEvaluation
]
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
return Alamofire.Manager(
configuration: configuration,
serverTrustPolicyManager: CustomServerTrustPolicyManager(policies: serverTrustPolicies)
)
}()
}
Also, I have added the below entry in info.plist but no luck.
<dict>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>myservice.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
<key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
<key>NSRequiresCertificateTransparency</key>
<true/>
</dict>
</dict>
</dict>
</dict>
Has anyone successfully connected self signed service using Alamofire & iOS9? Please advice.

Object #<Facebook> has no method 'initialize' Titanium Alloy

I have a problem with my Titanium app ... I looked for some tutorials on the internet and Appcelerator on facebook module, more specifically login / logout. I'm trying to adjust this error the day, but I can not in any way ... I am offering my project for download if you can download and test would be helpful!
I'm trying to log in to android, but the app has to be for ios too ... if you can tell me how I do for me two or indicate items that really work ....
Download my Project: http://we.tl/hqvEpb2aeG
Below my files:
Login.js
//Abir Fluxo de Caixa
function openFluxoDeCaixa(){
var winFluxo = Alloy.createController('fluxo').getView();
winFluxo.open();
}
fb.addEventListener('login', fbLogin);
$.btnLoginFacebook.addEventListener('click',function(e){
fb.authorize();
});
function fbLogin(e){
fb.removeEventListener('login', fbLogin);
if(e.success){
var fbdata = {};
fbdata = JSON.parse(e.data);
var uFoto = 'https://graph.facebook.com/' + fbdata.id + '/picture?width=300&height=300';
var uNome = fbdata.name;
var slipName = uNome.split(" ");
Ti.App.Properties.setString('logged', 'true');
Ti.App.Properties.setString('foto', uFoto);
Ti.App.Properties.setString('nome', slipName[0]);
openFluxoDeCaixa();
}
}
$.windowLogin.open();
Alloy.js
var fb = require('facebook');
fb.permissions = ['public_profile', 'read_stream'];
fb.appid = 172237596444060;
fb.forceDialogAuth = false;
fb.initialize();
if(OS_ANDROID){
$.windowLogin.fbProxy = fb.createActivityWorker({lifecycleContainer: $.windowLogin});
}
Alloy.Globals.LocalFunctions = {
setLogin : function setLogin(uId, uNome, uPlataforma){
var getLogin = Titanium.Network.createHTTPClient();
getLogin.open("POST","http://www.skrow.cc/ws-qia/controller.php");
var params = {
action: 'addLogin',
id: uId,
nome: uNome,
plataforma: uPlataforma
};
getLogin.send(params);
}
};
TiApp.xml
<?xml version="1.0" encoding="UTF-8"?>
<ti:app xmlns:ti="http://ti.appcelerator.org">
<id>br.com.queroinvestiragora</id>
<name>Quero Investir Agora</name>
<version>1.0</version>
<publisher>silviosampaio</publisher>
<url>http://www.queroinvestiragora.com.br</url>
<description>undefined</description>
<copyright>2015 by silviosampaio</copyright>
<icon>appicon.png</icon>
<fullscreen>false</fullscreen>
<navbar-hidden>false</navbar-hidden>
<analytics>true</analytics>
<guid>284edc0c-c599-4cae-9444-721cd3d22937</guid>
<property name="ti.ui.defaultunit" type="string">dp</property>
<ios>
<plist>
<dict>
<key>UISupportedInterfaceOrientations~iphone</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIRequiresPersistentWiFi</key>
<false/>
<key>UIPrerenderedIcon</key>
<false/>
<key>UIStatusBarHidden</key>
<false/>
<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleDefault</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.appcelerator.kitchensink</string>
<key>CFBundleURLSchemes</key>
<array>
<string>kitchensink</string>
<string>936940282991759</string>
</array>
</dict>
</array>
</dict>
</plist>
</ios>
<android xmlns:android="http://schemas.android.com/apk/res/android">
<manifest>
<application android:theme="#style/Theme.NoActionBar">
<activity android:label="#string/app_name"
android:name="com.facebook.LoginActivity" android:theme="#android:style/Theme.Translucent.NoTitleBar"/>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/app_id"/>
</application>
</manifest>
</android>
<mobileweb>
<precache/>
<splash>
<enabled>true</enabled>
<inline-css-images>true</inline-css-images>
</splash>
<theme>default</theme>
</mobileweb>
<modules>
<module platform="commonjs">ti.cloud</module>
<module platform="android" version="3.0.3">facebook</module>
<module platform="iphone" version="3.2.0">facebook</module>
</modules>
<deployment-targets>
<target device="android">true</target>
<target device="blackberry">false</target>
<target device="ipad">false</target>
<target device="iphone">true</target>
<target device="mobileweb">false</target>
</deployment-targets>
<sdk-version>3.5.1.GA</sdk-version>
<plugins>
<plugin version="1.0">ti.alloy</plugin>
</plugins>
<property name="appc-app-id" type="string">55ec85b523ec2d9730087189</property>
<property name="acs-authbase-url-development" type="string">https://secure-identity.cloud.appcelerator.com</property>
<property name="acs-base-url-development" type="string">https://api.cloud.appcelerator.com</property>
<property name="acs-oauth-secret-development" type="string">0VlBf7xO3Z3aWr2ISM6BXr2vxQH8OPaU</property>
<property name="acs-oauth-key-development" type="string">T8j8E5AOcEyUGOPtSZWaA4ygJLpi0pYL</property>
<property name="acs-api-key-development" type="string">5p3UAhCmk7I3H9lYzip5Wb97H0h9I38V</property>
<property name="acs-username-development" type="string">appc_app_user_dev</property>
<property name="acs-password-development" type="string">fUoxkjYTGqxoE8ZTJ0</property>
<property name="acs-authbase-url-production" type="string">https://secure-identity.cloud.appcelerator.com</property>
<property name="acs-base-url-production" type="string">https://api.cloud.appcelerator.com</property>
<property name="acs-oauth-secret-production" type="string">2JHJ4oZ4V0Ch5Gvy3GAnEkY4stnycUYn</property>
<property name="acs-oauth-key-production" type="string">UTUK7lzz2Vuq54fSAErTk4NaN3kghPOJ</property>
<property name="acs-api-key-production" type="string">3xGYGFJQAYXBK4quHslbKCfBtgAcCgXg</property>
<property name="acs-username-production" type="string">appc_app_user</property>
<property name="acs-password-production" type="string">rDD4YG0qQxtmdXg0yM</property>
<property name="appc-org-id" type="string">100026191</property>
<property name="appc-creator-user-id" type="string">baea2ab2-d377-4f02-aa1b-6b4553ffe12d</property>
</ti:app>
alloy.js is always executed when your app starts but variables you create inside it are not accessible from other controllers by default.
You will need to make your facebook module accessible in the global scope to access it outside alloy.js, you can do this by changing the following lines in alloy.js:
var fb = require('facebook');
fb.permissions = ['public_profile', 'read_stream'];
fb.appid = 172237596444060;
fb.forceDialogAuth = false;
fb.initialize();
To:
Alloy.Globals.fb = require('facebook');
Alloy.Globals.fb.permissions = ['public_profile', 'read_stream'];
Alloy.Globals.fb.appid = 172237596444060;
Alloy.Globals.fb.forceDialogAuth = false;
In login.js you also need to set the callback function for a successful facebook login before calling fb.initialize() Eg:
Alloy.Globals.fb.addEventListener('login', fbLogin);
Also you must set your login/logout functions before you try to call fb.initialize() or fb.authorize() so you will need to move fb.initialize() to login.js or just remove it from alloy.js since you are already calling fb.authorize().

Xamarin.Auth iOS9 Authentication SSL ERROR

I've just updated XCode to the 7.0 (7A220) and this take my Simulators to iOS9.
From that moment I cannot perform successfully any OAUTH call from the simulators.. I tried every model, from my App to the "sample Xamarin.Auth App".
The answer is always the same:
"Authentication Error
An SSL error has occurred and a secure connection to the server cannot be made"
The Code is the STANDARD one, I only changed my AppID.
The same code is working on the Android version of the same App!
var auth = new OAuth2Authenticator (
clientId: "my app id",
scope: "",
authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"),
redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html"));
auth.AllowCancel = allowCancel;
// If authorization succeeds or is canceled, .Completed will be fired.
auth.Completed += (s, e) =>
{
// We presented the UI, so it's up to us to dismiss it.
dialog.DismissViewController (true, null);
if (!e.IsAuthenticated) {
facebookStatus.Caption = "Not authorized";
dialog.ReloadData();
return;
}
// Now that we're logged in, make a OAuth2 request to get the user's info.
var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, e.Account);
request.GetResponseAsync().ContinueWith (t => {
if (t.IsFaulted)
facebookStatus.Caption = "Error: " + t.Exception.InnerException.Message;
else if (t.IsCanceled)
facebookStatus.Caption = "Canceled";
else
{
var obj = JsonValue.Parse (t.Result.GetResponseText());
facebookStatus.Caption = "Logged in as " + obj["name"];
}
dialog.ReloadData();
}, uiScheduler);
};
UIViewController vc = auth.GetUI ();
dialog.PresentViewController (vc, true, null);
The IOS9 Simulator can surf the web, so it is not a "connectivity problem". I also tried with Facebook SDK, same error. Could it be a certificate issue?
Thanks
To Fix this problem, simply add to your Info.plist file these lines:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>facebook.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
<key>fbcdn.net</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
<key>akamaihd.net</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
</dict>
If you don't care about extra rules for domains, you can simply add:
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>
NOTE: you have to Clean and Rebuild the project in order to see it running with these new settings!