iOs - 如何使用url将数据从Widget(今日扩展)传递到App?

时间:2016-10-18 12:31:59

标签: ios iphone swift widget today-extension

我正在尝试开发一个小部件(今天的扩展程序),它会向主应用程序传递一堆数据。

我在info.plist中添加了这个

<key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>TodayWidget</string>
            </array>
            <key>CFBundleURLName</key>
            <string>xxx.xxx.xxx</string>
        </dict>
    </array>

我用这段代码调用(成功)来自widget的应用程序

    let url = URL(string:"TodayWidget://?key=value")
    self.extensionContext?.open(url!, completionHandler: nil)

我如何访问这些值?

我也看到过这个,但xcode警告我代码已被弃用

Pass data between two Apps by url scheme in swift?

谢谢!

2 个答案:

答案 0 :(得分:0)

首先你的方案用法是错误的... CFBundleURLSchemes是从外面引用你的应用程序,而不是专门针对你的扩展。更好的用法是:

let url = URL(string:"yourAppName://TodayWidget?key=value")
let url = URL(string:"yourAppName://action?param1=value1&param2=value2")

然后你可以识别来源或行动...... 这里是从你的params获取字典的代码(url来自应用程序:openURL)

根据您的需求调整验证。

if (!url) return NO;
if ([url.absoluteString rangeOfString:@"://"].location == NSNotFound) return NO;
if ([url.absoluteString rangeOfString:@"?"].location == NSNotFound) return NO;

NSMutableDictionary* queryString = [NSMutableDictionary dictionaryWithCapacity:1];

__block NSMutableDictionary* paramDict = [[NSMutableDictionary alloc]init];
[paramDict setValue:[url scheme] forKey:@"protocol"];
[paramDict setValue:[url absoluteString] forKey:@"url"];
[paramDict setValue:[[url.absoluteString componentsSeparatedByString:@"://"][1] componentsSeparatedByString:@"?"].firstObject forKey:@"path"];
[paramDict setValue:queryString forKey:@"parameters"];

NSString* urlString = [url.absoluteString stringByRemovingPercentEncoding];
NSString* paramString = [urlString componentsSeparatedByString:@"?"][1];
NSArray* params = [paramString componentsSeparatedByString:@"&"];

for (NSString* param in params) 
{
    NSArray* paramArray = [param componentsSeparatedByString:@"="];
    if (paramArray.count != 2) {
        NSLog(@"Malformated url:%@", urlString);
        continue;
    }

    NSString* key = paramArray[0];
    NSString* value = paramArray[1];

    if (!key.length | !value.length) {
        NSLog(@"Malformated key %@ value %@ in url:%@", key, value, urlString);
        continue;
    }
    [queryString setValue:value forKey:key];
}
NSLog(@"%@", [paramDict toJSONString]);

答案 1 :(得分:0)

试试这个:

 let url = URL(string:"TodayWidget://value")
 self.extensionContext?.open(url!, completionHandler: nil)

要访问value中的Containing App

AppDelegate中,编写此方法:

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool
{
    if url.scheme == "NearbyRestaurantsTodayExtension"
    {
        if let value = url.host
        {
            //TODO: Write your code here
        }
    }
    return true
}